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?
-
As the default ComboBoxModel and ItemEvent does not let you get the previously selected value you could implement your own ComboBoxModel with this feature.
-
Foo oldFoo; .... fooCombo.addItemListener(new ItemListener() { public void itemStateChanged(final ItemEvent arg0) { Foo newFoo = (Foo) fooModel.getSelectedItem(); fooChangedHandler(oldFoo, newFoo); oldFoo = newFoo; } });Mark : I agree that this is the simplest solution. However, I suggested a custom ComboBoxModel as Kieran says he wants to use the proper Model-Delegate pattern as much as possible. I would say this breaks that pattern by keeping the last selected item outside the model. -
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()); } }
0 comments:
Post a Comment