GWT Listbox Multi Select
I need to add a listbox / combobox which allows the user to choose several values.
I know there is one already available in the GWT API ListBox with isMultipleSelect() set to true. But I am not getting any direct way to get all selected reocrds from list box.
Some tutorials on google are sugeesting implement Change开发者_C百科Handler
's onChange
method.
I think there should be some other way.
Any pointers would be appreciated.
You can go through the items in the ListBox
and call isItemSelected(int)
to see if that item is selected.
Create your own small subclass of ListBox
offering a method like
public LinkedList<Integer> getSelectedItems() {
LinkedList<Integer> selectedItems = new LinkedList<Integer>();
for (int i = 0; i < getItemCount(); i++) {
if (isItemSelected(i)) {
selectedItems.add(i);
}
}
return selectedItems;
}
The GWT API does not offer a direct way.
If you do not want to subclass the listbox, the following shows how to get the selected items from outside:
public void getSelectedItems(Collection<String> selected, ListBox listbox) {
HashSet<Integer> indexes = new HashSet<Integer>();
while (listbox.getSelectedIndex() >= 0) {
int index = listbox.getSelectedIndex();
listbox.setItemSelected(index, false);
String selectedElem = listbox.getItemText(index);
selected.add(selectedElem);
indexes.add(index);
}
for (Integer index : indexes) {
listbox.setItemSelected(index, true);
}
}
After the method has run the selected collection will contain the selected elements.
You have to iterate through all items in the ListBox
. The only shortcut is to iterate from the first selected item using getSelectedItem()
which return the first selected item in multi select ListBox
.
public List<String> getSelectedValues() {
LinkedList<String> values = new LinkedList<String>();
if (getSelectedIndex() != -1) {
for (int i = getSelectedIndex(); i < getItemCount(); i++) {
if (isItemSelected(i)) {
values.add(getValue(i));
}
}
}
return values;
}
精彩评论