GWT Listbox Multi Select

一个人想着一个人 提交于 2020-01-01 16:45:55

问题


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.


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/7248213/gwt-listbox-multi-select

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!