I have a function in a java class which gets triggers an action listener (as seen below):
// action event fired when hitting a checkbox
public void fireActionCheckBox(MyMainClass frame, JCheckBox theButtonExample) {
for(ActionListener a: theButtonExample.getActionListeners()) {
a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null) {
//Nothing need go here, the actionPerformed method (with the
//above arguments) will trigger the respective listener
});
}
}
Then i have a second function which does the same for a JButton's action listener:
// action event fired when hitting a button
public void fireActionButton(MyMainClass frame, JButton theButtonExample) {
for(ActionListener a: theButtonExample.getActionListeners()) {
a.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null) {
//Nothing need go here, the actionPerformed method (with the
//above arguments) will trigger the respective listener
});
}
}
I understand that in java the arguments must be assigned before it begins, but it seems inefficient to write the same code twice. Is there any better way to do this they would allow me not to write two functions for an action which is so similar.
Thank you for your help!
public void fireActionCheckBox(MyMainClass frame, AbstractButton button) { ... }
There is an abstract class AbstractButton which is a parent of both of these classes. It has defined the getActionListeners method.
Moreover, you could rewrite the method in a more generic way:
public <T extends AbstractButton> void fireActionButton(MyMainClass frame, T button) { ... }
You could pass to method a generics parameter rather than JCheckBox theButtonExample and JButton theButtonExample. For instance, assume both of the classes extends the same parent, you could do
public <J extends commonParent> void fireActionButton(MyMainClass frame, J j) {
//...
}
As @Sweeper indicated in the comments, since the parent does not have the listener, you will need to check type and do a downcasting:
public <J extends JComponent> void fireActionButton(MyMainClass frame, J j) {
if (j instanceof JComboBox) {
JCheckbox jbox = (JComboBox)j;
// Do something else
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With