Re: Setting properties on similar objects simultaneously
jackroofman@gmail.com wrote:
I need some way to work with a JButton and JToggleButton at the same
time. Is there some creative use of classes and typecasting that might
allow this?
The obvious common type is javax.swing.AbstractButton.
I'm not sure if there are any method signatures that are common between
JButton and JToggleButton, but not present in AbstractButton. There are
two (reasonable) general solutions to deal with such methods.
Introduce an interface, and extend each class to implement it:
interface CommonAbstractButton {
void setCommon(SomeType value);
}
class CommonButton extends JButton implements CommonAbstractButton {
CommonButton() {
super();
}
... other constructors ...
}
class CommonToggleButton extends JToggleButton implements
CommonAbstractButton {
...
}
Or, for more flexibility at the cost of more work, add a layer of
indirection:
abstract class CommonAbstractButton {
private final AbstractButton target;
protected CommonAbstractButton(AbstractButton target) {
if (target == null) {
throw new NullPointerException();
}
this.target = target;
}
public void setLabel(String label) {
target.setLabel(label);
}
public abstract void setCommon(SomeType value);
}
class CommonButton extends CommonAbstractButton {
private final JButton target;
public CommonButton(JButton target) {
super(target);
this.target = target;
}
public void setCommon(SomeType value) {
target.setCommon(value);
}
}
Tom Hawtin