eclipse中的GUI界面异常

0 java swing nullpointerexception actionlistener

我是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)
Run Code Online (Sandbox Code Playgroud)

有人能告诉我什么是错的吗?

Rei*_*eus 5

Button永远不会初始化类成员变量.而另一个具有不同名称(Java区分大小写)的go方法在本地方法中定义.

ActionListener你可以简单地使用ActionEvent源来确定来源Action:

public void actionPerformed(ActionEvent event) {

   JButton button = (JButton) event.getSource();
   button.setText("I have been clicked");
}
Run Code Online (Sandbox Code Playgroud)

这消除了将JButtonas作为类成员变量的需要.