Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!");
}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
531 views
Welcome To Ask or Share your Answers For Others

1 Answer

The reason is this Line:

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

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...