JButton.actionPerformed:空指针异常 [英] JButton.actionPerformed: null pointer exception

查看:293
本文介绍了JButton.actionPerformed:空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一本书,下面的代码在单击JButton时在运行时抛出一个NPE,在button.actionPerformed行。我已经尽力确保我的代码正是书中的内容,有人可以指出我的问题吗? (这本书是为java 5编写的,我使用的是最新的java 7,但据我所知,这在以下代码中应该没有区别)

I'm working through a book, and the following code throws a NPE at runtime when the JButton is clicked, at the line button.actionPerformed. I've done my best to be sure my code is exactly what is in the book, can someone point out my problem? (the book was written for java 5, I'm using the latest java 7, this shouldn't make a difference in the following code as far as I know though)

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

public class SimpleGui implements ActionListener {
JButton button;
public static void main(String[] args) {
    SimpleGui gui = new SimpleGui();
    gui.go();
}

public void go() {
    JFrame frame = new JFrame();
    JButton button = new JButton("click here");

    button.addActionListener(this);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.getContentPane().add(button);
    frame.setSize(300,300);
    frame.setVisible(true);
}

public void actionPerformed(ActionEvent event) {
    button.setText("I've been clicked, argh!");
}

}


推荐答案

原因是这一行:

JButton button = new JButton("click here");

在这里你要创建新的本地 JButton 对象 阴影 成员变量按钮。因此按钮仍然是 null 。你应该使用:

Here you are creating new local JButton object which is shadowing the member variable button . Hence button is still null. You should instead use:

button = new JButton("click here");

这篇关于JButton.actionPerformed:空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆