JCombobox - Only execute actionlistener when value changes

风流意气都作罢 提交于 2019-12-01 07:40:54

问题


I have a JComboBox, and I have a listener attached to it.

Right now every time the user "selects" something from the drop-down the event fires, even if they just reselected the value that was selected prior.

Is there any way to only fire the event if the selected value of the combo box is DIFFERENT than it was before it was selected?

I imagine I could store the value of the combo box in a different field, and compare it on event firing each time, this just seems kind of overkill. I have 20 or so such combo boxes. I'd rather not have 20 more variables JUST to store values so an event won't fire.

There has to be a better way.

Thank-you for your help!


回答1:


Have you considered using an ItemListener instead of an ActionListener?

 JComboBox<String> cb = new JComboBox<>(new String[] {"Stack", "Over", "Flow"});
 cb.addItemListener(new ItemListener() {
     @Override
     public void itemStateChanged(ItemEvent e) {
         System.out.println("Change");
     }
 });

It fires twice because one item becomes DESELECTED and another becomes SELECTED. Event fires for both. You can check which one occured by calling e.getStateChange().



来源:https://stackoverflow.com/questions/15353300/jcombobox-only-execute-actionlistener-when-value-changes

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