views:

292

answers:

2

In my code, two comboboxes are added to actionListener( this );

In another part of my code, I call a combobox function that sets an index to a certain value. This in turn calls actionPerfoemed again and so getSource == comboBox is true. Every time I call a set function it calls actionPerformed again, creating a stack of function calls that then unwinds down to the first.

Is there a way to prevent this?

+1  A: 

From the Swing tutorial,

Combo boxes also generate item events, which are fired when any of the items' selection state changes.

These events will be generated either when a user clicks on the items with the mouse, or when your software calls setSelectedIndex().

Perhaps you don't want your actionPerformed() method in this to be called when your software calls setSelectedIndex(). You may need a Boolean eventInitiatedBySoftware. In your main (this) class, you could say

synchronized(eventInitiatedBySoftware) {
  eventInitiatedBySoftware=true;
  comboboxeditor.setSelectedIndex(n);
}

and then in your listener:

public void actionPerformed(ActionEvent ae) {
synchronized(eventInitiatedBySoftware) {
  if (eventInitiatedBySoftware) {
    eventInitiatedBySoftware=false; // clear your flag.
    return; // don't want to process this event.
  }

  // the rest of your method goes here

}

When your software wants to adjust the value, it will set the Boolean to true. The actionPerformed method will be called, but your test will realise that this event was initiated by the software, and return before doing any of your existing code. It will clear the Boolean, so that if a user now uses the mouse to perform a selection action, your code will realise that it wasn't softwareInitiated.

BTW, It's possible that you misunderstand the event concept. For example, I suspect you are actually adding "this" as an event listener for each combobox, rather than adding comboboxes as listeners to "this". You might like to look at the Writing Event Listeners trail.

John
+1  A: 

If the problem is just the initial setting, you can defer adding the listener until after both have been initialized. There's more discussion here.

trashgod
Yes, that's exactly what's happening. Thanks for the link.
ShrimpCrackers
Excellent! Please consider accepting and/or up-voting this answer.
trashgod