gpt4 book ai didi

java - 来自另一个类的多个 JButton Action 监听器

转载 作者:太空宇宙 更新时间:2023-11-04 06:27:38 25 4
gpt4 key购买 nike

大家好,我有一个关于如何创建单独的 Action 监听器类的问题这是我现在的代码,工作正常,但不能满足我的需求。

for (int x = 0; x < buttons.length; x++) {
buttons[x] = new JButton(name[x]);
buttons[x].addActionListener(this);

}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttons[0]) {
//command
} else if (e.getSource() == buttons[1]) {
//command
}

}

所以基本上我希望这些按钮有一个来自另一个类的 Action 监听器。

最佳答案

再说一次,你的问题有点模糊,有点缺乏上下文。您已经知道可以使用任何实现 ActionListener 的类作为按钮的 ActionListener 或任何实现 Action(或扩展 AbstractAction)作为按钮的 Action 的类,并且很容易演示这一点:

import java.awt.event.ActionEvent;
import javax.swing.*;

public class ActionExample extends JPanel {
public static final String[] DAYS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};

public ActionExample() {
for (String day : DAYS) {
add(new JButton(new MyAction(day)));
}
}

private static void createAndShowGui() {
ActionExample mainPanel = new ActionExample();

JFrame frame = new JFrame("ActionExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

class MyAction extends AbstractAction {
public MyAction(String name) {
super(name);
}

@Override
public void actionPerformed(ActionEvent evt) {
System.out.println("Button pressed: " + evt.getActionCommand());
}
}

但我担心这仍然无法解决您遇到的我们尚未完全理解的问题。如果这个答案展示了如何使用外部类作为 Action(其功能作为 ActionListener),但没有回答您的问题,那么请再次提供更多上下文。

关于java - 来自另一个类的多个 JButton Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26572876/

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