Java multiple objects as an argument to a function
I have a function in a java class that calls triggers on an action listener (as shown 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 that does the same for the JButton 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, arguments must be assigned before they start, but it is inefficient to write the same code twice. Is there a better way to do this, they will prevent me from writing two functions for an action that looks so similar.
Thanks for your help!
source to share
public void fireActionCheckBox(MyMainClass frame, AbstractButton button) { ... }
There is an abstract class AbstractButton
that is the parent of both of these classes. He defined the method getActionListeners
.
Alternatively, you can rewrite the method in a more general way:
public <T extends AbstractButton> void fireActionButton(MyMainClass frame, T button) { ... }
source to share
You can pass a generics parameter to the method instead of JCheckBox theButtonExample
and JButton theButtonExample
. For example, suppose both classes extend the same parent, you could do
public <J extends commonParent> void fireActionButton(MyMainClass frame, J j) {
//...
}
As @Sweeper pointed out in the comments, since the parent doesn't have a listener, you need to check the type and downcast :
public <J extends JComponent> void fireActionButton(MyMainClass frame, J j) {
if (j instanceof JComboBox) {
JCheckbox jbox = (JComboBox)j;
// Do something else
}
}
source to share