Java JComboBox listen a change selection event [duplicate]

Deadly 提交于 2019-12-20 03:19:40

问题


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*/
}

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


回答1:


You can try itemStateChanged() method of the ItemListener interface:

class ItemChangeListener implements ItemListener{
    @Override
    public void itemStateChanged(ItemEvent event) {
       if (event.getStateChange() == ItemEvent.SELECTED) {
          Object item = event.getItem();
          // do something with object
       }
    }       
}

And add the listener to your JComboBox:

source.addItemListener(new ItemChangeListener());


来源:https://stackoverflow.com/questions/17576446/java-jcombobox-listen-a-change-selection-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!