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 m
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");
In a method, you have this:
JButton button = new JButton("click here");
This create the variable, but the scope of this new variable is inside the method. You've already declared button
in your class though. It should just be:
button = new JButton("click here");
You're shadowing your variables.
You declare button
as a class variable, but the re-declare within your go
method, meaning that the class variable (which you reference within your actionPerformed
method) is null
Change JButton button = new JButton("click here");
to button = new JButton("click here");
Well, your JButton button;
is still null
.you are not assigned it anywhere in your programm
This problem is known as "Variable Hiding" or "Hidden Variables" or "Shadowing Variables". Which means, a local variable hides another variable which has the same name. You have re defined your variable button
inside the go
method. Just removed the re definition from the go method, so it will work fine. Have a look at the following code
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();
button = new JButton("click here"); //Variable Re definition removed
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!");
}
}
Since you seems to be new to the Java GUI, take the following few advises.
private
is a good specifier for your button
variable