CellTable click swallowed - gwt

I've an combo box which is composed of a text field and a popup with a CellTable showing the suggestion items. The text field has a change handler that updates the CellTable's selection.
When typing a character and clicking an already selected suggestion, the first click is swallowed. The second click works and triggers the selection via the CellTable.addDomHandler(...).
Any idea why first click is swallowed?
Example code:
private static class SuggestFieldTextAndPopupSandbox extends SimplePanel {
private final TextField mText;
private CellTable<Handle<String>> mTable;
private SingleSelectionModel<Handle<String>> mTableSelection;
private SingleSelectionModel<Handle<String>> mSelection;
private ProvidesKey<Handle<String>> mKeyProvider = new SimpleKeyProvider<Handle<String>>();
private PopupPanel mPopup;
private List<Handle<String>> mData;
public SuggestFieldTextAndPopupSandbox() {
mData = Lists.newArrayList(new Handle<String>("AAA"), new Handle<String>("AAB"), new Handle<String>("ABB"));
mSelection = new SingleSelectionModel<Handle<String>>();
mText = new TextField();
mText.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent pEvent) {
mPopup.showRelativeTo(mText);
}
});
mText.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent pEvent) {
mTableSelection.setSelected(startsWith(mText.getValue()), true);
}
});
mText.addChangeHandler(new ChangeHandler() {
#Override
public void onChange(ChangeEvent pEvent) {
mText.setText(mText.getText().toUpperCase());
}
});
mTable = new CellTable<Handle<String>>(0, GWT.<TableResources>create(TableResources.class));
mTable.setTableLayoutFixed(false);
mTableSelection = new SingleSelectionModel<Handle<String>>(mKeyProvider);
mTable.setSelectionModel(mTableSelection);
mTable.addDomHandler(new ClickHandler() {
#Override
public void onClick(final ClickEvent pEvent) {
Scheduler.get().scheduleFinally(new ScheduledCommand() {
#Override
public void execute() {
mSelection.setSelected(mTableSelection.getSelectedObject(), true);
mText.setFocus(true);
mPopup.hide();
}
});
}
}, ClickEvent.getType());
mTable.addColumn(new TextColumn<Handle<String>>() {
#Override
public String getValue(Handle<String> pObject) {
return pObject.get();
}
});
mTable.setRowData(mData);
mPopup = new PopupPanel();
mPopup.setAutoHideEnabled(true);
mPopup.setWidget(mTable);
mPopup.setWidth("200px");
mPopup.setHeight("200px");
VerticalPanel p = new VerticalPanel();
p.add(mText);
setWidget(p);
}
private Handle<String> startsWith(final String pValue) {
final String val = nullToEmpty(pValue).toLowerCase();
int i = 0;
for (Handle<String> item : mData) {
String value = item.get();
if (value != null && value.toLowerCase().startsWith(val)) {
return item;
}
i++;
}
return null;
}
}

I reproduced your issue and here is the problem:
when you click on the suggestions the following is happening:
The text field is loosing focus which causes the corresponding ChangeEvent to be dealt with followed by the BlurEvent.
The click causes the popup to get the focus now which is why it is swallowed.
If you remove the ChangeHandler and the BlurHandler of the text field the issue disappears. But I think I found another solution
Try replacing the DOM handler of the mTable with a selection handler relative to the mTableSelection as follows:
mTableSelection.addSelectionChangeHandler(new Handler(){
#Override
public void onSelectionChange(SelectionChangeEvent event) {
Scheduler.get().scheduleFinally(new ScheduledCommand() {
#Override
public void execute() {
mSelection.setSelected(mTableSelection.getSelectedObject(), true);
mText.setFocus(true);
mPopup.hide();
}
});
}
});

Found a way how to properly solve this.
Skipping the blur handler when user hovers the suggestion list area seemed to fix that issue, at least from the tests that were done didn't see any more issues.
This was necessary because just before the user clicks a suggestion item, the text is blurred and it fires a selection change. This in turn cancels the selection made when user clicks an item.

Related

How to enable content proposal in NatTable TextCellEditor?

I am currently looking for content assist feature in Nattable TextCellEditor.I have found the way to attach the ContentProposalAdapter and IContentProposalProvider by extending the Nattable TextCellEditor. but ,The selected value from the proposed list is not updating in the text control.
Snippet :
#Override
protected Text createEditorControl(final Composite parent, final int Style) {
this.textControl = super.createEditorControl(parent, style);
contentProposalAdapter =
new ContentProposalAdapter(this.textControl, new TextContentAdapter(), contentProposalProvider, keyStroke,
null);
contentProposalAdapter.addContentProposalListener(new IContentProposalListener() {
#Override
public void proposalAccepted(IContentProposal proposal) {
System.out.println(proposal.getContent());
}
});
}
The problem you have is the internal FocusListener that is triggered while selecting a value in the popup. To add the support you also need to override the internal FocusListener with a listener that doesn't fire if the content proposal popup is open.
An example would be to add a boolean flag that indicates that the popup is open and add a listener that sets the flag accordingly.
private boolean popupOpen = false;
...
contentProposalAdapter.addContentProposalListener(new IContentProposalListener2() {
#Override
public void proposalPopupClosed(ContentProposalAdapter adapter) {
this.popupOpen = false;
}
#Override
public void proposalPopupOpened(ContentProposalAdapter adapter) {
this.popupOpen = true;
}
});
And then implement and set a FocusListener in the constructor that takes care of that flag.
this.focusListener = new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
if (!TextCellEditor.this.popupOpen) {
if (!commit(MoveDirectionEnum.NONE, true)) {
if (e.widget instanceof Control && !e.widget.isDisposed()) {
((Control) e.widget).forceFocus();
}
} else {
if (!TextCellEditor.this.parent.isDisposed())
TextCellEditor.this.parent.forceFocus();
}
}
}
};
In case the value should be immediately committed after it is selected, you need to add a listener that performs the commit after selection.
contentProposalAdapter.addContentProposalListener(new IContentProposalListener() {
#Override
public void proposalAccepted(IContentProposal proposal) {
commit(MoveDirectionEnum.NONE);
}
});
Unfortunately the AbstractCellEditor#InlineFocusListener is private and can therefore not be extended.
Feel free to file an enhancement ticket for NatTable to introduce the ability to easily add content proposals to a text cell editor.
https://bugs.eclipse.org/bugs/enter_bug.cgi?product=NatTable

Why can't I use GWT Button in a CellTable and how to combine cell buttons with cell text

I want to put some text and severals Buttons in a CellTable. I can display the text and buttons, but when I click on a button, nothing happens.
final SafeHtmlCell detailsCell = new SafeHtmlCell();
Column<UIRow, SafeHtml> detailsColumn = new Column<UIRow, SafeHtml>(
detailsCell) {
#Override
public SafeHtml getValue(UIRow object) {
String details = "some informations xxx <br/>";
Button addButton = new Button("Add value", new ClickHandler() {
public void onClick(ClickEvent event) {
Window.alert("hello");
}
});
details += addButton;
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant(details);
return sb.toSafeHtml();
}
};
detailsColumn.setCellStyleNames(CSS_DETAILS_TD);
table.setColumnWidth(detailsColumn, "10%");
table.addColumn(detailsColumn, new SafeHtmlHeader(SafeHtmlUtils.fromSafeConstant("details")));
But, if I put a Button per Cell, it's working, onClick method is called:
final ButtonCell btnCell = new ButtonCell() {
#Override
public void render(
final Context context,
final SafeHtml data,
final SafeHtmlBuilder sb) {
sb.appendHtmlConstant("<button type=\"button\" style=\"height: 25px\" title=\"submit\" class=\"btn btn-success btn-small\" tabindex=\"-1\">");
if (data != null) {
sb.append(data);
}
sb.appendHtmlConstant("</button>");
}
};
Column<UIRow, String> btnColumn = new Column<UIRow, String>(btnCell) {
#Override
public String getValue(UIRow object) {
return "";
}
};
btnColumn.setCellStyleNames("td-actions");
table.addColumn(btnColumn, "");
table.setColumnWidth(btnColumn, "5%");
btnColumn.setFieldUpdater(new FieldUpdater<UIRow, String>() {
public void update(int index, UIRow object, String value) {
...
service.submit(object, false, new AsyncCallback<String>() {
#Override
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
#Override
public void onSuccess(String result) {
Window.alert(result);
}
});
}
});
}
I want to display Html text and Buttons in one Col/Cell, is it possible ?
Thanks
Cell widgets (CellTable, DataGrid, etc) are not designed to embed regular GWT widgets like Button.
For buttons you can use ButtonCell
Take a look at official example:
http://samples.gwtproject.org/samples/Showcase/Showcase.html#!CwCellSampler
Update:
As for the second part of the question regarding how to combine cells, there is a few options:
Check out CompositeCell where you can combine multiple cells (eg ButtonCell and TextCell).
Another option is to use custom CellTableBuilder where you can customize all aspects of table rendering like colspans, column/row decorations, etc

Events of multiple cells in single column

I have two buttons(edit + delete) in one column.
ButtonCell functionButtonCell = new ButtonCell() {
#Override
public void render(final Context context, final SafeHtml data, final SafeHtmlBuilder sb) {
sb.appendHtmlConstant("<button type='button' class='gwt-Button' style = 'width:60px;margin:1px;'>Edit</button>");
sb.appendHtmlConstant("<br/>");
sb.appendHtmlConstant("<button type='button' class='gwt-Button' style = 'width:60px;margin:1px;'>Delete</button>");
}
};
functionColumn = new Column<AdminModel, String>(functionButtonCell) {
public String getValue(final AdminModel object) {
return object.getSeq().toString();
}
};
Bind event for this column in Presenter as
.........
view.getFunctionColumn().setFieldUpdater(new FieldUpdater<AdminModel, String>() {
public void update(final int index, final AdminModel object, final String value) {
Window.alert(index + "-" + value);
}
});
After clicked on edit button , alert-box has appeared , but not on delete button. When I clicked on delete button , nothing has appeared. What would be the problem ?
Addition: How can I decide which button was clicked by user (edit or delete) from my presenter ?
I would really appreciate any of your suggestions because I am troubled on it for a long times. Thanks!
ButtonCell filters events on the first child element only: https://gwt.googlesource.com/gwt/+/2.6.1/user/src/com/google/gwt/cell/client/ButtonCell.java This is why you don't get an event when clicking the second button (note: the goal of that code is to make sure you clicked on the button, and not on blank space around the button; see https://gwt.googlesource.com/gwt/+/a0dc88c8be7408be9554f746eb1ec93798183a28)
The easiest way to implement a two-button cell is to use a CompositeCell; it requires that child cells are rendered into sibling elements though (uses <span>s by default, example below overrides the rendering to use <div>s so your buttons stack each on its own line).
new CompositeCell<AdminModel>(Arrays.asList(
// First button
new HasCell<AdminModel, String>() {
#Override public Cell<String> getCell() { return new ButtonCell(); }
#Override public FieldUpdated<AdminModel, String> getFieldUpdater() {
return new FieldUpdater<AdminModel, String>() {
#Override public void update(int index, AdminModel object, String value) {
Window.alert("Edit " + object.getId());
}
};
}
#Override public String getValue(AdminModel o) {
return "Edit";
}
},
// Second button
new HasCell<AdminModel, String>() {
#Override public Cell<String> getCell() { return new ButtonCell(); }
#Override public FieldUpdated<AdminModel, String> getFieldUpdater() {
return new FieldUpdater<AdminModel, String>() {
#Override public void update(int index, AdminModel object, String value) {
Window.alert("Delete " + object.getId());
}
};
}
#Override public String getValue(AdminModel o) {
return "Delete";
}
}) {
#Override protected <X> void render(Cell.Context context, AdminModel value, SafeHtmlBuilder sb, HasCell<String,X> hasCell) {
// use a <div> instead of the default <span>
Cell<X> cell = hasCell.getCell();
sb.appendHtmlConstant("<div>");
cell.render(context, hasCell.getValue(value), sb);
sb.appendHtmlConstant("</div>");
}
};
(note: in your case, because the button's text doesn't depend on the row object, maybe you should rather use an ActionCell; it would better fit "semantically" with what you're doing, but otherwise it's almost the same; with an ActionCell, you'd use HasCell<AdminModel, AdminModel>, ActionCell<AdminModel>, getFieldUpdater would return null, and thegetValueof theHasCellwould just return theAdminModel` argument as-is).
Otherwise, implement your Cell (or AbstractCell) entirely by yourself.
Ideally, a column should have only one type of cell be it ImageCell, ButtonCell etc. Because all this ImageCell and ButtonCell does not provide any in-built events. The events are handled by FieldUpdater itself which does not have differentiators to identify that which ButtonCell is clicked. Ideally on click of that column, the field-updater will be called.
You should rather create your own composite widget which extends HasCell. This composite widget will have two different buttons and those in built methods are called on click of respective button.
public void onModuleLoad() {
CellTable<Person> table = new CellTable<Person>();
List<HasCell<Person, ?>> cells = new LinkedList<HasCell<Person, ?>>();
cells.add(new ActionHasCell("Edit", new Delegate<Person>() {
#Override
public void execute(Person object) {
// EDIT CODE
}
}));
cells.add(new ActionHasCell("Delete", new Delegate<Person>() {
#Override
public void execute(Person object) {
// DELETE CODE
}
}));
CompositeCell<Person> cell = new CompositeCell<Person>(cells);
table.addColumn(new TextColumn<Person>() {
#Override
public String getValue(Person object) {
return object.getName()
}
}, "Name");
// ADD Cells for Age and Address
table.addColumn(new Column<Person, Person>(cell) {
#Override
public Person getValue(Person object) {
return object;
}
}, "Actions");
}
private class ActionHasCell implements HasCell<Person, Person> {
private ActionCell<Person> cell;
public ActionHasCell(String text, Delegate<Person> delegate) {
cell = new ActionCell<Person>(text, delegate);
}
#Override
public Cell<Person> getCell() {
return cell;
}
#Override
public FieldUpdater<Person, Person> getFieldUpdater() {
return null;
}
#Override
public Person getValue(Person object) {
return object;
}
}
Also, see the link below.
[GWT CellTable-Need to have two buttons in last single cell of each row

Clear SuggestBox on blur in GWT

I have a SuggestionBox in GWT. Is there a way to clear it when it blurs (unless the user made a selection, in which case an action should happen)?
Add a BlurHandler:
suggestionBox.getValueBox().addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent event) {
// your code goes here
}
});
Try this one using ValueChangeHandler:
Note: ValueChange event has same behavior as Blue event but it is fired only if value is changed in SuggestBox.
class MyMultiWordSuggestOracle extends MultiWordSuggestOracle {
private Set<String> values = new HashSet<String>();
#Override
public void add(String value) {
super.add(value);
values.add(value);
}
#Override
public void clear(){
super.clear();
values.clear();
}
public boolean contains(String value) {
return values.contains(value);
}
}
You code:
final MyMultiWordSuggestOracle oracle = new MyMultiWordSuggestOracle();
oracle.add("A");
oracle.add("AB");
oracle.add("BCD");
oracle.add("BCDE");
final SuggestBox suggestionBox = new SuggestBox(oracle);
suggestionBox.addValueChangeHandler(new ValueChangeHandler<String>() {
#Override
public void onValueChange(ValueChangeEvent<String> event) {
if (!oracle.contains(event.getValue())) {
suggestionBox.setValue("");
}
}
});

GWT: how can i add/remove a button in a celltable on the go

I have this button cell in my CellTable
ButtonCell reListCell = new ButtonCell();
reListColumn = new Column<EmployerJobs, String>(reListCell) {
#Override
public String getValue(EmployerJobs object) {
return "ReList";
}
};
ctJobs.addColumn(reListColumn,
EmployerDashBoardConstants.EMPTYHEADERCOLUMN);
but i only want this cell to be appear if the below condition pass
public void getDateDiff(final EmployerJobs object) {
rpcService.getDateDiff(object.getJobValidDate(), new AsyncCallback<Boolean>() {
public void onFailure(Throwable caught) {
}
public void onSuccess(Boolean jobExpired) {
if(jobExpired) {
// HERE I WANT TO SHOW MY RELISTCELL, means if the job is expired only then
// there will be a button showing relist would be appear in that row ,for
// the jobs which are not expired NO button should appear..
}
}
});
}
how can i achieve this?
thanks
I agree with DTing.
Quering the backend for each cell/row is not really efficient.
I would rather put the info (jobExpired) into your EmployerJobs class and transfer the info when you request the list of your EmployerJobs to be displayed in your CellTable.
You can update the list periodically to account for changes (see the expenses sample on how to do that).
But to your initial question (hiding the cell). There are two solutions:
Use an ActionCell and override the render method.
ActionCell:
ActionCell<EmployerJobs> reListCell = new ActionCell<EmployerJobs>("ReList",
new ActionCell.Delegate<EmployerJobs>() {
#Override
public void execute(EmployerJobs object) {
// code to be executed
}
})
{
#Override
public void render(Cell.Context context,EmployerJobs value,SafeHtmlBuilder sb) {
if (value.isJobExpired()) // isJobExpired returns the field jobExpired.
super.render(context,value,sb);
}
};
reListColumn = new Column<EmployerJobs, EmployerJobs>(reListCell) {
#Override
public String getValue(EmployerJobs object) {
return object;
}
};
ctJobs.addColumn(reListColumn,
EmployerDashBoardConstants.EMPTYHEADERCOLUMN);
Use a ButtonCell and override the render method of your Column.
ButtonCell:
ButtonCell reListCell = new ButtonCell();
reListColumn = new Column<EmployerJobs, String>(reListCell) {
#Override
public String getValue(EmployerJobs object) {
return "ReList";
}
#Override
public void render(Cell.Context context,EmployerJobs object,SafeHtmlBuilder sb) {
if (value.isJobExpired()) // isJobExpired returns the field jobExpired.
super.render(context,value,sb);
}
};
ctJobs.addColumn(reListColumn,
EmployerDashBoardConstants.EMPTYHEADERCOLUMN);
Just tried Umit solution #2 ButtonCell. It works!
To link an specific action to the button, reListColumn.setFieldUpdater(new FieldUpdater....
would be needed
I tried ButtonCell solution too. But if you click in a cell who as no button then an error on client side occur:
com.google.gwt.core.client.JavaScriptException: (TypeError) #com.google.gwt.core.client.impl.Impl::apply(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)([JavaScript object(445), JavaScript object(240), JavaScript object(637)]): parent is null
So I added this to override the Event and avoid Event if I want:
#Override
public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context context,
Element parent, YourObject object, NativeEvent event) {
if (object.isCompleted())
super.onBrowserEvent( context, parent, object, event);
}
I don't know if it's the better way to do it but it works.