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.
    }
}

关于java - JComboBox itemStateChanged事件一次调用两次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21926397/

10-09 10:08