java GWT 列表框多选
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7248213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
GWT Listbox Multi Select
提问by Hardik Mishra
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 ListBoxwith isMultipleSelect() set to true. But I am not getting any direct way to get all selected reocrds from list box.
我知道 GWT API ListBox 中已经有一个 isMultipleSelect() 设置为 true。但是我没有得到从列表框中获取所有选定记录的任何直接方法。
Some tutorials on google are sugeesting implement ChangeHandler
's onChange
method.
谷歌上的一些教程正在使用 sugeesting 工具ChangeHandler
的onChange
方法。
I think there should be some other way.
我认为应该有其他方式。
Any pointers would be appreciated.
任何指针将不胜感激。
回答by Zoltan Balazs
You can go through the items in the ListBox
and call isItemSelected(int)
to see if that item is selected.
您可以浏览ListBox
和 调用中的项目isItemSelected(int)
以查看是否选择了该项目。
回答by z00bs
Create your own small subclass of ListBox
offering a method like
创建您自己的小子类,ListBox
提供类似的方法
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.
GWT API 不提供直接方式。
回答by Julian Dehne
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.
该方法运行后,所选集合将包含所选元素。
回答by JuanFran Adame
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
.
您必须遍历ListBox
. 唯一的快捷方式是从第一个选定的项目开始迭代,使用getSelectedItem()
它返回 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;
}