2017-04-27 127 views
3

我在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开始前的参数必须指定,但它似乎没有效率的两次写相同的代码。有没有更好的方法来做到这一点,他们会允许我不写两个功能来执行类似的操作。

谢谢你的帮助!

+3

提示:是否有共同的父类een'JButton'和'JCheckBox'? –

+0

也许你可以在一个单独的类中使用for循环作为方法,然后在这两个地方调用 – wylasr

+0

@Joe C - yes'JComponent'是'JButton'和'JCheckBox'的父类,但我无法使用'.getActionListeners()'带有'JComponent' – JFreeman

回答

3
public void fireActionCheckBox(MyMainClass frame, AbstractButton button) { ... } 

有一个抽象类AbstractButton这是这两个类的父。它已经定义了getActionListeners方法。

此外,你可以在一个更通用的方法重写方法:

public <T extends AbstractButton> void fireActionButton(MyMainClass frame, T button) { ... } 
+0

将它作为第二个例子显示出来会带来什么好处? – JFreeman

+1

@JFreeman,它只是看起来更有表现力,没有什么区别,直到你使用具有某种层次结构的类型集合。 – Andrew

+0

好的,谢谢! – JFreeman

2

您可以传递给方法a 泛型参数而不是JCheckBox theButtonExampleJButton theButtonExample。例如,假设两个类扩展了相同的父,你可以做

public <J extends commonParent> void fireActionButton(MyMainClass frame, J j) { 
    //... 
} 

由于@Sweeper在评论中指出的,由于父母没有听众,你将需要检查类型做一个向下转换

public <J extends JComponent> void fireActionButton(MyMainClass frame, J j) { 
    if (j instanceof JComboBox) { 
    JCheckbox jbox = (JComboBox)j; 
    // Do something else 
    } 
} 
+2

问题是,'JButton'和'JComboBox' - 'JComponent'的常见父项没有'getActionListeners'方法。 – Sweeper

+0

你说得对。我认为在这种情况下,我们需要检查方法中的对象类型。尽管如此,我认为这比两次写同样的方法要好:P – PhoenixPan

1

JCheckBox的和JButton的都是同一个父类的孩子的:

enter image description here

定义与方法两者的超类:

public void fireActionAbstractButton(MyMainClass frame, AbstractButton myAbstractButton) { 
     System.out.println(myAbstractButton.getClass().getName()); 
    } 
+0

是的这有效! (我不幸只能标记一个答案是正确的) – JFreeman