Gwt ListBox MultipleSelect

当ListBox设置属性MultipleSelect时取值方法如下:

package com.cn.client;

import java.util.ArrayList;
import java.util.List;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;


public class TestGWT implements EntryPoint {
  public void onModuleLoad() {
    VerticalPanel v = new VerticalPanel();
    HorizontalPanel h = new HorizontalPanel();
    VerticalPanel vp = new VerticalPanel();
    final Label tagLabel = new Label();
    final ListBox listBox = new ListBox();
    listBox.addItem("first","1");
    listBox.addItem("second","2");
    listBox.addItem("three","3");
    listBox.addItem("four","4");
    listBox.addItem("five","5");
    listBox.setMultipleSelect(true);
    listBox.setHeight("11.5em");

   
    Button okButton = new Button();
    okButton.setText("提交");
    vp.add(okButton);
    vp.add(tagLabel);
    h.add(listBox);
    h.add(vp);
   
    okButton.addClickHandler(new ClickHandler(){
@Override
public void onClick(ClickEvent event) {
List<Integer> selectedItems = new ArrayList<Integer>();
String sb = new String();
for (int i = 0; i < listBox.getItemCount(); i++) {
        if (listBox.isItemSelected(i)) {
            selectedItems.add(i);
            sb +="值: " + listBox.getItemText(i) + "  --  ID:" + i;
            System.out.println("值:"+listBox.getItemText(i));
        }
}
tagLabel.setText(
"select:"+ sb
);
}
    });
    v.setCellWidth(h, "500px");
    v.add(h);
    RootPanel.get("root").add(v);
  }
 
//   ListBox 获得index的值
  public List<Integer> getSelectedItems(ListBox listBox) {
    List<Integer> selectedItems = new ArrayList<Integer>();
    if(listBox.isMultipleSelect()){
    for (int i = 0; i < listBox.getItemCount(); i++) {
        if (listBox.isItemSelected(i)) {
            selectedItems.add(i);
        }
    }
}
    return selectedItems;
}
}


你可能感兴趣的:(listbox)