I have a view that has several “flag” buttons (JToggleButton). When the user clicks a flag button, I want to update an array that keeps track of which buttons are flagged. This is pretty simple, and here is what I have done:
...
bflag[i].addItemListener(this); //View listens to state change
...
void itemStateChange(ItemEvent ie) {
try {
jtb = (JToggleButton)ie.getSource();
//Update mark array
}
catch (ClassCastException cce) {}
}
This works just fine, but it is ugly with the try/catch. I would much prefer to do something like this:
void itemStateChange(ItemEvent ie) {
handleStateChange(ie.getSource());
}
void handleStateChange(JToggleButton jtb) {
//handle state change
}
void handleStateChange(Object o) {}
This is much nicer, but the only problem is that the Object method will fire even if the source is a JToggleButton (because a JToggleButton is an Object after all).
I have also considered using double dispatch, but this would require overriding the JToggleButton method that fires itemStateChange(), and I don’t know what that is (and that seems unsafe).
Any suggestions on how to get this to work without a try/catch, conditional check, etc.?
You will have to check for the Type explicitly I think.
Alternatively you can use anonymous inner classes to implement your listeners and avoid having to check the source altogether.
Something like this: