我有一个 JComboBox ,我附加了一个监听器。
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?
我想我可以将组合框的值存储在不同的字段中,并且比较每次事件发生时,这看起来有点矫枉过正。我有20个左右这样的组合框。我宁愿不再有20个变量来存储值,所以事件不会触发。
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.
必须有更好的方法。
感谢您的帮助!
推荐答案您是否考虑过使用ItemListener而不是ActionListener?
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"); } });它会触发两次因为一个项目变为DESELECTED而另一个变为SELECTED。两件事都引发了火灾。你可以通过调用 e.getStateChange()来检查发生了哪一个。
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().
更多推荐
JCombobox
发布评论