Java JComboBox侦听更改选择事件

Java JComboBox侦听更改选择事件,java,selection,jcombobox,Java,Selection,Jcombobox,我试图在JavaJComboBox中听到选择的变化。我曾尝试使用ActionListener,但问题是:ActionListener会做类似的事情 public void actionPerformed(ActionEvent e){ JComboBox<String> source = ((JComboBox<String>)e.getSource()); String selected = source.getItemAt(source.getSele

我试图在JavaJComboBox中听到选择的变化。我曾尝试使用ActionListener,但问题是: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*/
}
public void actionPerformed(ActionEvent e){
JComboBox source=((JComboBox)e.getSource());
选定字符串=source.getItemAt(source.getSelectedIndex());
/*现在我比较所选字符串是否与其他字符串相等
在一些情况下,我必须向组合添加元素*/
}
正如您所注意到的,当我需要向组合添加元素时,会触发另一个事件并再次调用actionPerformed方法,即使我不希望这样,代码可能会循环…:( 有没有办法只听选择更改而不听一般更改事件?
谢谢

您可以尝试接口的
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());