Click to See Complete Forum and Search --> : Filtering JComboBox events


Buck Naked
September 29th, 1999, 04:33 PM
Hi,
I'm using a JComboBox as a "master list" of available elements to choose from. The problem I'm having is that is how they react to events. I've tried both actionListeners and itemListeners to detect user selections, but for some reason, if I select the same item from the list twice (consecutively), it will not detect. I have to actually select another item from the list before it will detect the previous item. Does anyone have any ideas on how to work around this?
p.s. The JList component does the same thing as well :(

meherss
September 30th, 1999, 01:15 PM
That's how they are desinged ( Someone thinks this is wrong pl. correct me ).
Event change happens only on the selection of the new item.
If you want to achieve what you are looking then you have to write your own class JMyComboBox extends JComboBox then you have an option to fire an event changed. Other than that, In don't think you can do this.

Meher

Buck Naked
October 1st, 1999, 10:47 AM
Hey Meher,
appreciate your tip. It worked! :D

Here's what I had to do (in case anyone else has the same problem in the future).

import javax.swing.*;
import java.awt.event.*;

public class TSComboBox extends JComboBox {

private Object selectedItem = null;

public TSComboBox(String[] branches) {
super(branches);
}

public void resetSelectedItemReminder() {
super.selectedItemReminder = null;
}

}



It turns out that the JComboBox component uses an Object reference called selectedItemReminder to keep track of the previously selected item. All that was necessary was to reset this reference to null, forcing the combobox to "think" there was NO previously selected item.
I also had to write my itemListener to detect ItemEvent.SELECTED so it would fire appropriately for any selection in the list (even a previously selected item).
Thanks again!

Buck Naked
November 10th, 1999, 08:59 AM
Someone has also pointed out to me that the line :
private Object selectedItem = null;


is not necessary...Thanks Shantala!

The code should be as follows:

import javax.swing.*;
import java.awt.event.*;

public class TSComboBox extends JComboBox {

public TSComboBox(String[] comboListItems) {
super(comboListItems);
}

public void resetSelectedItemReminder() {
super.selectedItemReminder = null;
}
}



The method resetSelectedItemReminder()

should be called in whatever event handler you decide to use (I used an ItemListener as in the example below):

comboList = new TSComboBox(listItems);
comboList.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
selectedItem = new String(ie.getItem().toString());
comboList.resetSelectedItemReminder();
}
}
});

add(comboList, gbConstraints);



Thanks again Meher!