Question

I'm trying to write a nice GUI in Swing that uses the proper Model-Delegate pattern as much as possible. I have a JComboBox that when changed, needs to update the model with the new data. To get the currently selected item, I am using:

fooCombo.addItemListener(new ItemListener() {
    public void itemStateChanged(final ItemEvent arg0) {
        fooChangedHandler((Foo) fooModel.getSelectedItem());
    }
});

Which returns what the data was changed to as a nice Object. However, I can't find a way to find out the old value, so I don't know which object needs to be changed. Any ideas here?

Was it helpful?

Solution

ended up not going to the model at all but getting my object from the getItem method like so:

public void itemStateChanged(final ItemEvent event) {
    if (event.getStateChange() == event.DESELECTED) {
        deselectedFoo = (Foo) event.getItem();
    } 
    else if (event.getStateChange() == event.SELECTED) {
        FooChangedHandler(deselectedFoo,(Foo) event.getItem());
    }
}

OTHER TIPS

Foo oldFoo;
....
fooCombo.addItemListener(new ItemListener() {
    public void itemStateChanged(final ItemEvent arg0) {
        Foo newFoo = (Foo) fooModel.getSelectedItem();
        fooChangedHandler(oldFoo, newFoo);
        oldFoo = newFoo;
    }
});

As the default ComboBoxModel and ItemEvent does not let you get the previously selected value you could implement your own ComboBoxModel with this feature.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top