JComboBox Events and communication

F

f

I have two JComboBox, box1 and box2. box2 is dependent on box1.

1. I populate box1 with two selections "Color" and "Shape"
2. box2 is blank.
3. If use select "Color" in box1, I populate box2 with selections
"Red" and "Green".
4. If use select "Shape" in box1, I populate box2 with two selections
"Circle" and "Rectangle".
5. User select box2...


I handle the itemStateChanged event of both box1 and box2, here is my
code"

void box1_itemStateChanged(ItemEvent e) {
box2.removeAllItems();
String item = box1.getSelectedItem().toString();
if (item.equalsIgnoreCase("Color")){
box2.addItem("Red");
box2.addItem("Green");
}else{
box2.addItem("Cirlce");
box2.addItem("Rectangle");
}

}

void box2_itemStateChanged(ItemEvent e) {
String item = box2..getSelectedItem.toString();
...
}

I found a problem here. When I call box2.addItem("Red"), the method
box2_itemStateChanged was called and the program goes inside this
method and everything was messed up. How do I block box2 from sending
event where I am in box1_itemStateChanged(ItemEvent e) populating
box2?

Thanks,

ff
 
S

Steve Claflin

If I understand what you are saying, the problem is that the a combo
box, in this case the second one, fires itemStateChanged when the first
item is loaded, because it is by default the selected item at that
point. There are two ways I have handled this:

1. remove the second box event handler as the first step in the first
box event handler, then set it again as the last step
2. keep a boolean variable around, something like box2Loading, that you
set to true when box 2 is loading, and false when loading is done --
then test box2Loading in your box 2 event handler
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top