不太了解JComboBox itemListeners

时间:2012-10-04 01:39:58

标签: java swing jcombobox itemlistener

所以,如果我有一个组合框“box”,并且它设置的数组的值为“hello”和“world”, 我如何选择哪一个被选中?

3 个答案:

答案 0 :(得分:1)

box.getSelectedItem();

返回选中的对象。这是javadoc:http://docs.oracle.com/javase/6/docs/api/javax/swing/JComboBox.html

答案 1 :(得分:1)

在传递给ItemListener

的ItemEvent上调用getItem()

答案 2 :(得分:1)

您可以使用getSelectedItem()获取所选的一个。

String name[] = {"One","Two","Three","Four"};
JComboBox combo = new JComboBox(name);
combo.addItemListener(new ItemListener(){
   public void itemStateChanged(ItemEvent ie){
       String str = (String)combo.getSelectedItem();
       System.out.println("Selected Item is: " + str);
   }
});