Java JComboBox监听更改选择事件 [英] Java JComboBox listen a change selection event
问题描述
我正在尝试在Java JComboBox中监听选择的更改。我试图使用ActionListener但问题是这样的:动作监听器做这样的事情
I'm trying to listen to a change of selection in a Java JComboBox. I have tried to use an ActionListener but the problem is this: the action listener does something like this
public void actionPerformed(ActionEvent e){
JComboBox<String> source = ((JComboBox<String>)e.getSource());
String selected = source.getItemAt(source.getSelectedIndex());
/*now I compare if the selected string is equal to some others
and in a couple of cases I have to add elements to the combo*/
}
您可以注意到,当我需要向组合添加元素时,会触发另一个事件并调用actionPerformed方法再次,即使我不想这样,代码可能循环... :(
有没有办法只听取选择更改而不是通用更改事件?
谢谢
As you can notice, when I need to add elements to the combo another event is fired and the actionPerformed method is called again, even if I don't want that, and the code may loops... :( Is there any way to listen to the selection change only and not to a generic change event? Thanks
推荐答案
你可以尝试<$ h $ c> itemStateChanged() ItemListener 界面:
class ItemChangeListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
// do something with object
}
}
}
并将监听器添加到JComboBox:
And add the listener to your JComboBox:
source.addItemListener(new ItemChangeListener());
这篇关于Java JComboBox监听更改选择事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!