问题
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