gpt4 book ai didi

java - 如何添加监听多个按钮的 Action 监听器

转载 作者:IT老高 更新时间:2023-10-28 21:10:00 25 4
gpt4 key购买 nike

我正试图找出我对 Action 监听器做错了什么。我正在关注多个教程,但当我尝试使用 Action 监听器时,netbeans 和 eclipse 给了我错误。

下面是一个简单的程序,我试图让一个按钮在其中工作。

我做错了什么?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;


public class calc extends JFrame implements ActionListener {



public static void main(String[] args) {

JFrame calcFrame = new JFrame();

calcFrame.setSize(100, 100);
calcFrame.setVisible(true);

JButton button1 = new JButton("1");
button1.addActionListener(this);

calcFrame.add(button1);
}

public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1)
}

}

Action 监听器从未注册,因为使用 if(e.getSource() == button1) 它看不到 button1,错误提示找不到符号。

最佳答案

静态方法中没有 this 指针。 (我不相信这段代码甚至会编译。)

你不应该在像 main() 这样的静态方法中做这些事情;在构造函数中进行设置。我没有编译或运行它来查看它是否真的有效,但试一试。

public class Calc extends JFrame implements ActionListener {

private Button button1;

public Calc()
{
super();
this.setSize(100, 100);
this.setVisible(true);

this.button1 = new JButton("1");
this.button1.addActionListener(this);
this.add(button1);
}


public static void main(String[] args) {

Calc calc = new Calc();
calc.setVisible(true);
}

public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1)
}

}

关于java - 如何添加监听多个按钮的 Action 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5936261/

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