My code is quite simple actually. I saw a simple and similar code was from this article.
At first, I have 1 combobox. I have a listener on it called itemStateChanged(). My purpose to add into this listener is that; "to execute some code when user click (select) an item from its dropbox".
Cmb_ItemCategory = new javax.swing.JComboBox();
Cmb_ItemCategory.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Loading..." }));
Cmb_ItemCategory.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
Cmb_ItemCategoryItemStateChanged(evt);
}
});
private void Cmb_ItemCategoryItemStateChanged(java.awt.event.ItemEvent evt) {
if(evt.getStateChange() == java.awt.event.ItemEvent.SELECTED){
System.err.println("Sombody click or change my model content");
}
}
Behind the code, I grab some data, and then calling a method of removeAllItems() . And then I set a new Model (from new data) into it.
-- at another line of code ---
Cmb_ItemCategory.removeAllItems();
Cmb_ItemCategory.setModel(newModel);
I juz realized that my itemStateChanged() is called when i do the removeAllItem() method. called once.
So, How to make it only called once user Click (select) only AND not when removeAllItems() called?
it similar to this article. But it's not removingItems case. CMIIW.
As nIcE cOw already illustrated in his example, it should certainly work when you use a
DefaultComboBoxModel
(which is the case in his sample code, although it happens behind the screens).I could explain the behavior you encounter for the non-
DefaultComboBoxModel
case, although your code snippet suggests you use one. Looking at the source code forJComboBox#removeAllItems
there is a different code path since theremoveAllElements
method is not part of theMutableComboBoxModel
interfaceSo with a non-
DefaultComboBoxModel
you are going to remove the items one by one. This means that at a certain point in time, you will remove the selected element. A possible implementation of your model might change the selected element at that point. If you look for example at the implementation inDefaultComboBoxModel
(although this code will not be triggered) you can clearly see it changes the selection.Perhaps your model does something similar, which explains the event. Just for making this post complete, the code behind the
DefaultComboBoxModel#removeAllElements
where you can clearly see it sets the selection tonull
and does not select another object. Only weird thing in that code is that it does not fire aDESELECTED
event first, although you know the selection has changed if you listen for theintervalRemoved
event ... but that is not really relevant to your problemSo to conclude: I say the solution for your problem is located in your model, and not in the code you posted