gpt4 book ai didi

java多个对象作为函数的参数

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:39:53 24 4
gpt4 key购买 nike

我在 java 类中有一个函数可以触发一个 Action 监听器(如下所示):

// 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 监听器执行相同的操作:

// 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 中必须在开始之前分配参数,但是将相同的代码写两次似乎效率很低。有没有更好的方法来做到这一点,他们允许我不为一个如此相似的 Action 编写两个函数。

感谢您的帮助!

最佳答案

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

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

此外,您可以用更通用的方式重写该方法:

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

关于java多个对象作为函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43650262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com