Hardik Mishra
Hardik Mishra

Reputation: 14877

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 ChangeHandler's onChangemethod.

I think there should be some other way.

Any pointers would be appreciated.

Upvotes: 3

Views: 14534

Answers (4)

JuanFran Adame
JuanFran Adame

Reputation: 39

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;
}

Upvotes: 0

Julian Dehne
Julian Dehne

Reputation: 21

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.

Upvotes: 2

z00bs
z00bs

Reputation: 7498

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.

Upvotes: 3

Zoltan Balazs
Zoltan Balazs

Reputation: 837

You can go through the items in the ListBox and call isItemSelected(int) to see if that item is selected.

Upvotes: 5

Related Questions