我正在尝试在Java JComboBox中监听选择的更改。我试图使用ActionListener,但问题是:动作监听器做了类似这样的事情
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方法,即使我不想要它,并且代码可能循环... :( 有没有办法只听取选择更改而不是通用更改事件? 感谢
答案 0 :(得分:8)
您可以尝试ItemListener界面的itemStateChanged()
方法:
class ItemChangeListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
// do something with object
}
}
}
将侦听器添加到JComboBox:
source.addItemListener(new ItemChangeListener());