我是 Java 新手,目前通过 HeadFirst java 书自学。 我正在使用 GUI 界面,书中的代码似乎无法运行,
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui1 implements ActionListener {
JButton Button;
public static void main(String[] args) {
SimpleGui1 gui = new SimpleGui1();
gui.go();
}
public void go(){
JFrame frame = new JFrame();
JButton button = new JButton("click me");
button.addActionListener(this);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed (ActionEvent event) {
Button.setText("I have been clicked");
}
}
The exception :
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
谁能告诉我出了什么问题吗?
最佳答案
类成员变量Button
从未被初始化。相反,另一个具有不同名称的(Java 区分大小写)是在 go
方法中本地定义的。
在 ActionListener
中,您可以简单地使用 ActionEvent
源来确定 Action
的源:
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
button.setText("I have been clicked");
}
这样就不再需要将 JButton
作为类成员变量。
关于java - eclipse中GUI界面异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16224348/