我试图找出我对动作监听器做错了什么。我正在遵循多个教程,但当我尝试使用操作侦听器时,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)
}
}
动作监听器永远不会被注册,因为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)
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)