JButton.actionPerformed: null pointer exception

后端 未结 5 634
抹茶落季
抹茶落季 2020-12-21 22:47

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

相关标签:
5条回答
  • 2020-12-21 23:08

    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");
    
    0 讨论(0)
  • 2020-12-21 23:16

    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");
    
    0 讨论(0)
  • 2020-12-21 23:20

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

    0 讨论(0)
  • 2020-12-21 23:22

    Well, your JButton button; is still null.you are not assigned it anywhere in your programm

    0 讨论(0)
  • 2020-12-21 23:25

    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.

    1. It is always a best practice to define your class variables inside the constructor
    2. Use access specifiers. private is a good specifier for your button variable
    3. Even though the constructor can be automatically get created (default constructor) it is a best practice to code it by your self, at least a blank one.
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题