gpt4 book ai didi

java - JComboBox itemStateChanged 事件一次调用两次

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:54 24 4
gpt4 key购买 nike

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 事件。

参见 this tutorial page关于如何编写 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.
}
}

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com