itemStateChanged事件一次调用两次

itemStateChanged事件一次调用两次

本文介绍了JComboBox itemStateChanged事件一次调用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

为什么在组合框中选择项目时会调用此事件两次。?

Why this event is called twice when selecting item in combobox.?

推荐答案

JComoboBox会调用ItemListener一次改变两次。一次用于SELECTED事件,一次用于DESELECTED事件。

JComoboBox ItemListener does get called twice for a single change. Once for SELECTED event and once for DESELECTED event.

参见关于如何编写ItemListener。

See this tutorial page on how to write an ItemListener.

基本上你需要做的是

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

这篇关于JComboBox itemStateChanged事件一次调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:50