resultCombo = new JComboBox(); resultCombo.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent ie) { sampleText=resultCombo.getSelectedItem().toString(); System.out.println("SampleText : "+sampleText); } }); output: SampleText : selectedword SampleText : selectedword
为什么在组合框中选择项目时会调用此事件两次.
解决方法
对于单个更改,JComoboBox ItemListener会被调用两次.一次用于SELECTED事件,一次用于DESELECTED事件.
有关如何编写ItemListener的信息,请参见this tutorial page.
基本上你要做的就是
public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { //Do any operations you need to do when an item is selected. } else if(e.getStateChange() == ItemEvent.DESELECTED){ //Do any operations you need to do when an item is de-selected. } }