Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I don't want to use ActionListener or ItemListener because those also fire when I select an item through the program. And I can't use MouseListener either because it only fires when I click the JComboBox, not when I select an item.

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. And in my action listener, it only executes if the flag is false.

like image 750
fent Avatar asked Nov 06 '22 05:11

fent


1 Answers

A) I would recommend you to temporarily remove the listener when you perform the selection programatically.

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

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

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. In the action listener you simply add an

if (nonUserSelection)
    return;
like image 158
aioobe Avatar answered Nov 09 '22 09:11

aioobe