3

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!

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Doug
  • 6,446
  • 9
  • 74
  • 107
  • Generally speaking. No. You could use the [`JComboBox#putClientProperty`](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#putClientProperty%28java.lang.Object,%20java.lang.Object%29) to store the previously selected value and use `JComboBox#getClientProperty` to retrieve it and compare to the changing value...as a thought – MadProgrammer Mar 12 '13 at 04:31
  • 1
    This: http://stackoverflow.com/questions/58939/jcombobox-selection-change-listener might help you. It seems similar kind of question to me. – Harry Joy Mar 12 '13 at 04:32

1 Answers1

9

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().

mostruash
  • 4,169
  • 1
  • 23
  • 40
  • This seems to work. For some reason it appears to be firing twice on me, but that could be because of something else I have going on right now. Thank-you! – Doug Mar 12 '13 at 04:42
  • I had actually just figured that out. Thanks! That will be easy to change behavior on. This should solve a lot of problems! – Doug Mar 12 '13 at 04:48