setting a default text to a GWT ListBox - gwt

I am trying to create a ListBox using GWT. I am using UiBinder to create the field.
I would like to set a default text on the list box and when a user clicks on the box, it should show me the list items. Once again, if user has not selected any option, it should show me the default text again.
Any way to do this either using Uibinder or some ListBox methods?

If I understand correctly you want a value to show but when the user clicks on the list it disappears and shows you the list items?
As far as I know there is no option to that natively.
What you can do is add the first item to hold your default value.
You can do this grammatically by using addItem in code or using:
<g:Listbox>
<g:item value="-1">Default text</g:item>
</g:Listbox>
works with gwt 2.1+
The value can still be selected.
You can choose to ignore it or add an attribute "disabled" with value "disabled" to the option element:
listbox.getElement().getFirstChildElement().setAttribute("disabled" ,"disabled" )
hope it helps a bit :)

You can also use a renderer to control what is shown if 'Null' is selected.
(Inspired by: How do I add items to GWT ListBox in Uibinder .ui.xml template ?)
private class SimpleRenderer implements Renderer<T>{
private String emptyValue = "Select a value";
#Override
public String render(T val) {
if(val == null) {
return emptyValue;
}
return val.toString();
}
#Override
public void render(T val, Appendable appendable) throws IOException {
appendable.append(render(val));
}
public void setEmptyValue(String emptyValue) {
this.emptyValue = emptyValue;
}
}

Related

Dynamically add widgets in a cell to represent "tags" in Datagrid

In a GWT web app, I am using a DataGrid to manage elements from a database. I represent a list of elements as rows, the columns being editable fields of their characteristics (id, name, description). I am mostly using the EditTextCell class.
I now want to create a custom cell, for a column that has to represent a list of "tags" that can be attached to every element. From this cell, tags could be added, using a + button (that makes a drop-down menu appear or something), and deleted. Each tag should be a kind of button, or interactive widget (I later want to display pop-up with info, trigger actions, etc).
Actually, it would not be so different from the "tags" bar on the Stack Overflow website...
So I have been looking for a solution:
I thought this would be easy to do. I imagined just putting a FlowPanel in the cell, adding/removing Buttons/Widgets dynamically. But it turns out that in GWT Widgets and Cells and very different objects apparently..
I read making use of the AbstractCell class to create a custom cell allows to do anything, but its working is very low level and obscure to me.
I saw that CompositeCell allows to combine various cell widgets into one cell, but I have not found if it is possible to do it dynamically, or if the widgets are going to be the same for all lines throughout a column. I mostly saw examples about, for instance, how to put two Buttons in every cell of a single column.
What is the easiest way to implement what I need?
EDIT:
So, after some tests, I am going for Andrei's suggestion and going "low-level", creating a custom cell extending AbstractCell<>. I could create an appropriate "render" function, that generates a list of html "button", and also attaches Javascript calls to my Java functions when triggering a Javascript event (onclick, onmouseover, onmouseout...).
It is working pretty well. For instance, by clicking the "+" button at the end a tag list, it calls a MenuBar widget that presents the list of tags that can be added.
But I am struggling to find a way to update the underlying data when adding a tag.
To sum up:
I have a CustomData class that represents the data I want to display in each line of the table. It also contains the list of tags as a Set.
ModelTable (extends DataGrid) is my table.
CustomCell (extends AbstractCell) can renders the list of tags as several buttons on a line.
A click on a "+" button in a cell makes a AddTagMenu popup drop down, from which I can click on the tag to add.
How do I update the content of the cell?
I tried playing around with onBrowserEvent, onEnterKeyDown, bus events... with no success. At best I can indeed add a tag element to the underlying object, but the table is not updated.
It's not possible to meet your requirements without going really "low-level", as you call it.
It's relatively easy to create a cell that would render tags exactly as you want them. Plus icon is also easy, if this is the only action on the cell. However, it is very difficult to make every tag within a cell an interactive widget, because the DataGrid will not let you attach handlers to HTML rendered within a cell. You will need to supply your own IDs to these widgets, and then attach handlers to them in your code. The problem, however, is that when the DataGrid refreshes/re-renders, your handlers will most likely be lost. So you will have to attach them again to every tag in every cell on every change in the DataGrid.
A much simpler approach is to create a composite widget that represents a "row", and then add these "rows" to a FlowPanel. You can easily make it look like a table with CSS, and supply your own widget that looks like a table header. You will need to recreate some of the functionality of the DataGrid, e.g. sorting when clicked on "column" header - if you need this functionality, of course.
As you have already noted, using CompositeCell could be a way to get what you want.
The idea is to create a cell for every tag and then (during rendering) decide which one should be shown (rendered). Finally combine all those cells into one by creating a CompositeCell.
The main disadvantage of this solution is that you need to know all possible tags before you create a DataGrid.
So, if you have a fixed list of possible tags or can get a list of all existing tags and this list is reasonably small, here is a solution.
First, we need to know which tag is represented by a column so I extended a Column class to keep information about a tag. Please, note that TagColumn uses ButtonCell and also handles update when the button is clicked:
public class TagColumn extends Column<DataType, String> {
private TagEnum tag;
public TagColumn(TagEnum tag) {
super(new ButtonCell());
this.tag = tag;
setFieldUpdater(new FieldUpdater<DataType, String>() {
#Override
public void update(int index, DataType object, String value) {
Window.alert("Tag " + getTag().getName() + " clicked");
}
});
}
public TagEnum getTag() {
return tag;
}
#Override
public String getValue(DataType object) {
return tag.getName();
}
}
Then create a cell for each tag (I have hard-coded all tags in a TagEnum):
List<HasCell<DataType, ?>> tagColumns = new ArrayList<HasCell<DataType, ?>>();
for(TagEnum tag : TagEnum.values())
tagColumns.add(new TagColumn(tag));
Now, the most important part: decide either to show the tag or not - overwrite render method of the CompositeCell:
CompositeCell<DataType> tagsCell = new CompositeCell<DataType>(tagColumns) {
#Override
protected <X> void render(Context context, DataType value, SafeHtmlBuilder sb, HasCell<DataType, X> hasCell) {
if(value.getTagList().contains(((TagColumn) hasCell).getTag()))
super.render(context, value, sb, hasCell);
else
sb.appendHtmlConstant("<span></span>");
}
};
This is important to always render any element (for example empty span when the tag should not be shown). Otherwise the CompositeCell's implemantation will get confused when accessing sibling elements.
Finally, full, working example code:
private DataGrid<DataType> getGrid() {
DataGrid<DataType> grid = new DataGrid<DataType>();
List<HasCell<DataType, ?>> tagColumns = new ArrayList<HasCell<DataType, ?>>();
for(TagEnum tag : TagEnum.values())
tagColumns.add(new TagColumn(tag));
CompositeCell<DataType> tagsCell = new CompositeCell<DataType>(tagColumns) {
#Override
protected <X> void render(Context context, DataType value, SafeHtmlBuilder sb, HasCell<DataType, X> hasCell) {
if(value.getTagList().contains(((TagColumn) hasCell).getTag()))
super.render(context, value, sb, hasCell);
else
sb.appendHtmlConstant("<span></span>");
}
};
Column<DataType, DataType> tagsColumn = new Column<DataType, DataType>(tagsCell) {
#Override
public DataType getValue(DataType object) {
return object;
}
};
grid.addColumn(tagsColumn, "Tags");
grid.setRowData(Arrays.asList(
new DataType(Arrays.asList(TagEnum.gwt)),
new DataType(Arrays.asList(TagEnum.table, TagEnum.datagrid)),
new DataType(Arrays.asList(TagEnum.datagrid, TagEnum.widget, TagEnum.customCell)),
new DataType(Arrays.asList(TagEnum.gwt, TagEnum.table, TagEnum.widget, TagEnum.customCell)),
new DataType(Arrays.asList(TagEnum.gwt, TagEnum.customCell)),
new DataType(Arrays.asList(TagEnum.gwt, TagEnum.table, TagEnum.datagrid, TagEnum.widget, TagEnum.customCell))
)
);
return grid;
}
public class TagColumn extends Column<DataType, String> {
private TagEnum tag;
public TagColumn(TagEnum tag) {
super(new ButtonCell());
this.tag = tag;
setFieldUpdater(new FieldUpdater<DataType, String>() {
#Override
public void update(int index, DataType object, String value) {
Window.alert("Tag " + getTag().getName() + " clicked");
}
});
}
public TagEnum getTag() {
return tag;
}
#Override
public String getValue(DataType object) {
return tag.getName();
}
}
public class DataType {
List<TagEnum> tagList;
public DataType(List<TagEnum> tagList) {
this.tagList = tagList;
}
public List<TagEnum> getTagList() {
return tagList;
}
}
public enum TagEnum {
gwt ("gwt"),
table ("table"),
datagrid ("datagrid"),
widget ("widget"),
customCell ("custom-cell");
private String name;
private TagEnum(String name) {
this.name = name;
}
public String getName() {
return name;
}
}

GWT: CheckBoxCell and Selection change event

I am using the following constructor to create a checkboxcell in an editable data grid.
CheckboxCell(false, true)
When I use this and click at any place in the row, selection change event does not fire and I am using single selection model .
When I use,
CheckboxCell();
Selection change event fires on the row but,
1) We have click twice to check or uncheck the cell.
2) if we check or uncheck in the checkboxcell, the value will reverted as soon as I click anywhere.
I am trying to figure out the solution, but not successful yet. Any help would be appreciated.
Am using GWT 2.4.0
The problem is because of selection if possible do not use selection model. and add field updater for the column of check box. I have used this:
Column< GridReportFields, Boolean > cb = new Column< GridReportFields, Boolean >(new CheckboxCell() ) {
#Override
public Boolean getValue(GridReportFields object) {
// TODO Auto-generated method stub
return object.getCheckb();
}
};
cb.setFieldUpdater(new FieldUpdater<GridReportFields, Boolean>() {
#Override
public void update(int index, GridReportFields object, Boolean value) {
// TODO Auto-generated method stub
object.setCheckb(value);
dataGrid.redraw();
}
});
here gridReport Field is my model class. and setCheckb is is setter for the boolean variable that holds the value of checkbox.

How to hide suggestions in GWT SuggestBox?

I am using GWT 2.4. I have a Suggestbox and I have a requirement to hide the suggestion list under certain cases. The context is as below.
After user selects a suggestion from suggestion list, I am populating two other text box fields, with values corresponding to the selection. For example, suppose the suggestbox contains user-names, and user selects a user-name from suggestions, then other two fields, say user address and email are populated in two other text boxes. These two fields are read only now. Then user clicks on an 'Edit' button. Now the user can edit either user- name ( ie edit in suggestion box), user address and email. It doesn't make sense to show the suggestions again when the user is editing the user-name, since the user has already selected the user and decided to edit it. In a nutshell my SuggesBox should behave as a normal text box. I tried following code, (I know hideSuggestionList() is deprecated) but its not working.
display.getSuggestBox().hideSuggestionList();
Reading the javadoc for hideSuggestionList() it is said that, "Deprecated. use DefaultSuggestionDisplay.hideSuggestions() instead". I don't know how to use DefaultSuggestionDisplay, and I'm using SuggestBox with 'MultiWordSuggestOracle'.
Thanks for helping me out!!
What you can do is simply swap the SuggestionBox with a normal TextBox when the user clicks edit and back when edit is closed. Also because if you would hide the suggestions list, it still queried from the server. By swapping the widget you don't have to care about side effects. SuggestionBox itself uses also a TextBox and thus for the user it's not visible the widget has changed.
If you don't use your own SuggestionDisplay, then this should Just Work™:
((DefaultSuggestionDisplay) suggestBox.getSuggestionDisplay()).hideSuggestions();
Here is the Solution
My Entry Point Class
public class SuggestionEntryPoint implements EntryPoint {
#Override
public void onModuleLoad() {
SuggestBoxWidget suggestBoxWidget = new SuggestBoxWidget();
RootPanel rootPanel = RootPanel.get();
suggestBoxWidget.createOracle();
suggestBoxWidget.createWidgetAndShow(rootPanel);
rootPanel.add(suggestBoxWidget);
DOM.getElementById("loader").removeFromParent();
}
}
And here is my Widget
public class SuggestBoxWidget extends Composite {
private TextBox textSuggestBox = new TextBox();
private SuggestBox suggestBox = null;
DefaultSuggestionDisplay suggestionDisplay = new DefaultSuggestionDisplay();
MultiWordSuggestOracle suggestOracle = new MultiWordSuggestOracle();
private static SuggestBoxWidgetUiBinder uiBinder = GWT
.create(SuggestBoxWidgetUiBinder.class);
interface SuggestBoxWidgetUiBinder extends
UiBinder<Widget, SuggestBoxWidget> {
}
public SuggestBoxWidget() {
initWidget(uiBinder.createAndBindUi(this));
}
public void registerEvents(){
suggestBox.addKeyUpHandler(new KeyUpHandler() {
#Override
public void onKeyUp(KeyUpEvent event) {
if(suggestBox.getText().equalsIgnoreCase("1")){
suggestionDisplay.hideSuggestions();
}
}
});
}
public void createWidgetAndShow(HasWidgets container){
suggestBox = new SuggestBox(suggestOracle,textSuggestBox,suggestionDisplay);
container.clear();
container.add(suggestBox);
registerEvents();
}
public void createOracle(){
for(int i=1;i<=100;i++){
suggestOracle.add(i+"");
}
}
}
Actually you have to create a SuggestBox with 3 Parameters to the Constructor.

Add SuggestBox to CellTable as an editable cell

Is there any way to SuggestBox to CellTable? Maybe there is another solution then SuggestBox?
I need to get an editable cell with suggestion feature?
I'm using GWT 2.4.
I don't think you can add it directly in. Try using a ClickableTextCell as the cell for that column. Then code your ValueUpdater (which will be called when the cell is clicked) to open up a DialogBox. Put your SuggestBox, and other widgets (OK button, Cancel button, and such), inside that DialogBox. Initialize the SelectionBox with the current contents of the cell. The DialogBox will likely be a DialogBox subclass with extra state data you initialize with the object for that CellTable row as well as the field for that column, so that the OK action knows what field on what object to update with the new contents of the SuggestBox. Essentially it's a popup editor. Not ideal, because users will expect the editor to be embedded in the CellTable, but there are only a few cell editors available (EditTextCell, DatePickerCell, SelectionCell and CheckboxCell, and maybe another variant of text editing), but I've used this technique, and really, it's not too bad.
I ended up using FlexTable instead of CellTable. With FlexTable you may put any widget inside a table cell.
I needed this also and found a solution (under testing, but solong it is working):
I copied the Code from TextInputCell into a new Class SuggestBoxTextInputCell
public class SuggestBoxTextInputCell extends AbstractInputCell<String, SuggestBoxTextInputCell.ViewData> {
MySuggestBox suggestBox;
and added some lines to the onBrowserEvent method:
// Ignore events that don't target the input.
InputElement input = getInputElement(parent);
String eventType = event.getType();
if (BrowserEvents.FOCUS.equals(eventType)) {
TextBox textBox = new MyTextBox(input);
suggestBox = new MySuggestBox(getSuggestOracle(), textBox);
suggestBox.onAttach();
}
Element target = event.getEventTarget().cast();
The classes MySuggestBox and MyTextbox exist only to make the needed constructor and methods public:
private class MyTextBox extends TextBox {
public MyTextBox(Element element) {
super(element);
}
}
private class MySuggestBox extends SuggestBox {
public MySuggestBox(SuggestOracle suggestOracle, TextBox textBox) {
super(suggestOracle, textBox);
}
#Override
public void onAttach() {
super.onAttach();
}
}
getSuggestOracle() only delivers the needed SuggestOracle. Hope someone can use this solution.
I needed this as a solution so I play around with the solution provided by Ande Hofer.
The exact same issue met by Ankit Singla, when the suggestbox is working fine when I press "Enter" key, but not from the "Mouse Click".
I go on further and add-on this onto the solution.
if (BrowserEvents.FOCUS.equals(eventType)) {
...
...
suggestbox.addSelectionHandler(new SelectionHandler<Suggestion>() {
#Override
public void onSelection(SelectionEvent<Suggestion> event) {
Suggestion selectedSuggestion = event.getSelectedItem();
String selectedValue = selectedSuggestion.getReplacementString();
onSuggestSelected(input, selectedValue, valueUpdater);
}
});
suggestbox.onAttach();
}
and a private function
private void onSuggestSelected(Element input, String value,
ValueUpdater<String> valueUpdater) {
input.blur();
suggestbox.onDetach();
if (suggestbox.getSuggestionDisplay().isSuggestionListShowing()) {
((DefaultSuggestionDisplay) suggestbox.getSuggestionDisplay()).hideSuggestions();
}
valueUpdater.update(value);
}
So far so good.

Menu bar in gwt

I am using MenuBar control in gwt and want to get the selected item. I read the API document API document for MenuBar but could not find any method that could help me. Please tell me the way how can I trap the selected item of the MenuBar.I want to get the selected item when the user click on it.
The answer to your question is Command.
http://google-web-toolkit.googlecode.com/svn/javadoc/2.3/com/google/gwt/user/client/Command.html.
When you add an item to the menubar (or to any of its children) you specify
Command helloCmd = new Command() {
public void execute() {
Window.alert("Hello");
}
};
addItem("Hello", helloCmd);
or
menuItem.setCommand(helloCmd);
You could also execute the command independent of any menu items:
helloCmd.execute();
I don't see why the method getSelectedItem() wouldn't work. Maybe it is because you want to have the item when the user clicks? Just create your MenuItems with a Command that asks the MenuBar which item is selected. Maybe it might even be better to use a separate command for some of your items.
Nico
I've the same problem and solved as follow:
public class CustomMenuBar extends MenuBar {
public CustomMenuBar(boolean isVertical) {
super(isVertical);
}
public MenuItem getSelected() {
return super.getSelectedItem();
}
public void clearSelected() {
super.selectItem(null);
}
}
and you can check it for null (if not null then clear it)