I have 2 JComboBox controls filled with items initially. Selecting one item in a JComboBox moves it to the other JComboBox.
The problem occurs when one of the JComboBox controls is empty. When I try to move an item to an empty JComboBox it triggers its actionPerformed event.
private void leftComboActionPerformed(java.awt.event.ActionEvent evt) {
Object selectedItem = leftCombo.getSelectedItem();
leftCombo.removeItem(selectedItem);
rightCombo.addItem(selectedItem);
}
private void rightComboActionPerformed(java.awt.event.ActionEvent evt) {
Object selectedItem = rightCombo.getSelectedItem();
rightCombo.removeItem(selectedItem);
leftCombo.addItem(selectedItem);
}
Why does adding an item to the empty JComboBox do that? It doesn’t fire when an item is added to it when it’s filled.
How to prevent the event from firing when it’s empty?
The following piece of code dumps the stack trace
The relevant part of it
If you then look in the source code, you can see that when adding an element it will be selected when there is currently nothing selected
Changing the selection might cause the firing of an
ActionEvent. If you follow the source code there is no mechanism to disable this. You could however disable your listener before you add the element, and enable it afterwards.