Reputation: 13
I am doing a desktop application where I need that when the user click or select an specific item (lest say "SHOW.DIALOG.ITEM") of a JComboBox
triggers a listener that open a new JDialog
that I use to configure that item. The code in 1 shows how I do it with a ItemListener
and it works fine in showing the JDialog
. In another part of the application where I load the values of the combo box (see code 2) I set to the JComboBox
that the selected value is the specific item that shows the dialog and of curse it shows the dialog to the user because the combo box has the ItemListener
and the if() condition,but the problem is that in my application I do not want that behavior to happen in that moment, i just want to happen only when the user select the item in the combo box. That is why I try to add an OnClickMouse
listener instead of the ItemListener
because I believe that may resolve my problem, but I can not find how to add a mouse listener to the comboBox
that works like I want (I have try the addMouseListener
with an onClick
MouseAdapter
but it do not work in showing the dialog). If anyone has a better idea of how I should do this or a way to adding an OnMouseClick
listener to the comboBox
that emulates the wanted behavior,it will be very helpful. Thanks
1) Adding item listener to the comboBox
that shows the dialog
after selecting the item
comboBox.addItemListener(e -> {
if (ItemEvent.SELECTED == e.getStateChange()) {
String valueAfterSelection = e.getItem().toString();
if (valueAfterSelection.equalsIgnoreCase("SHOW.DIALOG.ITEM")) {
dialog.setVisible(true);
}
}
}
2) Setting to the comboBox
the specific item (this open the dialog and I do not want that to happen in that moment)
String value = reader.readComboBoxValue();
if (value.equalsIgnoreCase("SHOW.DIALOG.ITEM")) {
comboBox.setSelectedItem(value);
}
Upvotes: 1
Views: 597
Reputation: 324118
You can always remove the listener before changing the selection:
comboBox.removeItemListener(...);
comboBox.setSelectedItem(value);
comboBox.addItemListener(...);
This means you would need to keep a reference to the listener when you create it, so you can easily remove/add as needed.
Upvotes: 2