JCombobox

编程入门 行业动态 更新时间:2024-10-28 20:21:14
本文介绍了JCombobox - 仅在值更改时执行actionlistener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 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

本文发布于:2023-10-26 11:16:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529971.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JCombobox

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!