java - 如何在 Java 中将 ActionListener 添加到框架中的按钮

标签 java swing jframe jbutton actionlistener

我正在尝试测试按钮,但我无法让 Action Listener 工作

public class ButtonTester implements ActionListener {

static JLabel Label = new JLabel("Hello Buttons! Will You Work?!");
public static void main(String[] args) {
    //Creating a Label for step 3
    // now for buttons
    JButton Button1 = new JButton("Test if Button Worked");
    // step 1: create the frame
    JFrame frame = new JFrame ("FrameDemo");
    //step 2: set frame behaviors (close buttons and stuff)
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //step 3: create labels to put in the frame
    frame.getContentPane().add(Label, BorderLayout.NORTH);
    frame.getContentPane().add(Button1, BorderLayout.AFTER_LAST_LINE);
    //step 4: Size the frame
    frame.pack();
    //step 5: show the frame 
    frame.setVisible(true);
    Button1.setActionCommand("Test");
    Button1.setEnabled(true);
    Button1.addActionListener(this); //this line here won't work
}
@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if("Test".equals(e.getActionCommand()))
    {
        Label.setText("It Worked!!!");
    }
  }

}

最佳答案

静态方法不与类的实例相关联,因此不能使用 this

您可以将所有代码从 main 移动到 ButtonTester 的非静态方法(例如,run())并从 main 执行类似这样的操作:

new ButtonTester().run();

您还可以为 ActionListener 使用匿名内部类:

Button1.addActionLister(new ActionListener() {
    @Override public void actionPerformed (ActionEvent e) {
        // ... 
    }
});

关于java - 如何在 Java 中将 ActionListener 添加到框架中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18093548/

相关文章:

java - Aspectj 切面指定多个包

java - Tomcat 7 问题 - 无法启动服务器实例

java - 有没有办法在执行时减慢翻译动画的速度?

java - 如何编写启动画面?

java - 建立JFrame的语法。哪个是对的?

java - Intent 额外和 Intent 数据之间有什么区别?

Java文本后面的竖线?就像编辑器中指示页面结束位置的行一样

java - 选择某些元素后使 Swing JMenuBar 树保持打开状态

java - 使用另一个类中的 jbutton 调用带有绘制和线程的 main 方法

java - 从另一个 JFrames 构造函数创建 JFrame