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.@H_502_5@
基本上你要做的就是@H_502_5@
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. } }