简体   繁体   English

当USER选择JComboBox中的项目时,如何创建一个触发器

[英]How do I make a listener that fires when the USER selects an item in a JComboBox

I'm looking for a listener that fires ONLY when the user, the one who's using the program, selects an item in the JComboBox . 我正在寻找一个仅在用户(使用该程序的用户)选择JComboBox的项目时JComboBox触发的侦听器。 I don't want to use ActionListener or ItemListener because those also fire when I select an item through the program. 我不想使用ActionListenerItemListener因为当我通过程序选择项目时,它们也会触发。 And I can't use MouseListener either because it only fires when I click the JComboBox , not when I select an item. 而且我也不能使用MouseListener ,因为它只在我单击JComboBox时触发,而不是在我选择项目时触发。

I was wondering what the easiest way to do this is? 我想知道最简单的方法是什么? Currently, my solution is messy. 目前,我的解决方案很混乱。 When I change the selected item of the jcombobox through code, I set a flag to true. 当我通过代码更改jcombobox的选定项目时,我将标志设置为true。 And in my action listener, it only executes if the flag is false. 在我的动作监听器中,只有在标志为false时才会执行。

A) I would recommend you to temporarily remove the listener when you perform the selection programatically. A)我建议您在以编程方式执行选择时临时删除侦听器。

B) If your programatic change is not an effect of another GUI event you could solve it the following ugly/non-robust/error-prone/"hacky" way: Check EventQueue.isEventDispatchThread() to find out if the click was triggered by the GUI thread (the user). B)如果您的程序更改不是另一个GUI事件的影响,您可以使用以下丑陋/非健壮/容易出错/“hacky”方式解决它:检查EventQueue.isEventDispatchThread()以查明是否触发了点击GUI线程(用户)。

C) (Oops I just reread your question and saw that you've already discovered the method described below. Basically I would say that this (or the the method described above) is your best alternative.) C) (哎呀我只是重新阅读你的问题,看到你已经发现了下面描述的方法。基本上我会说这个(或上面描述的方法)是你最好的选择。)

Another option is to have a boolean flag called something like nonUserSelection which you set to true before you select a value programatically and reset to false afterwards. 另一种选择是使用一个名为nonUserSelection的布尔标志,在以编程方式选择值并在之后重置为false之前将其设置为true。 In the action listener you simply add an 在动作监听器中,您只需添加一个

if (nonUserSelection)
    return;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM