我在Java类它得到具有这样的功能触发一个动作侦听器(如下所示):java的多个对象作为参数为函数
// 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
});
}
}
然后我具有不相同为一个第二功能JButton的动作侦听器:
// 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
});
}
}
据我所知,在Java开始前的参数必须指定,但它似乎没有效率的两次写相同的代码。有没有更好的方法来做到这一点,他们会允许我不写两个功能来执行类似的操作。
谢谢你的帮助!
提示:是否有共同的父类een'JButton'和'JCheckBox'? –
也许你可以在一个单独的类中使用for循环作为方法,然后在这两个地方调用 – wylasr
@Joe C - yes'JComponent'是'JButton'和'JCheckBox'的父类,但我无法使用'.getActionListeners()'带有'JComponent' – JFreeman