-5

代码给出了空指针异常的错误.....要做什么?

import java.awt.event.*;
import javax.swing.*;

public class Gui implements ActionListener{
JButton button;

public Gui(){
    JFrame frame=new JFrame();
    JButton button =new JButton("click me!");
    button.addActionListener(this);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(button);
    frame.setSize(270,300);
    frame.setVisible(true);
}
public static void main(String[] args){
    new Gui();
}

public void actionPerformed(ActionEvent e){
    button.setText("I've been clicked");
}

}
4

3 回答 3

12
JButton button =new JButton

这将创建一个局部变量。场依旧
buttonnull

于 2012-06-04T19:45:28.250 回答
5

您在 actionPerformed 方法中引用的字段button从未初始化,因此为空。

您在 main 方法中添加了这个按钮JButton button =new JButton("click me!");,但您的 actionPerformed 从未意识到这一点。

更改要读取的行

this.button =new JButton("click me!");

于 2012-06-04T19:48:10.430 回答
4

您的问题是该按钮仅在构造函数中可见。

于 2012-06-04T19:45:13.520 回答