JAVA: Swing JButton componnent (NullPointerExcepti

2019-08-08 18:08发布

问题:

I am trying to show text - "You pressed Button" when you pressed one of buttons.
I am getting an NullPointerException. I have initialized the buttons inside the constructor of the class and after initialization, I called the following method from main().

Here is the code:

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

public class ButtonDemo implements ActionListener{
    JLabel jlab;

    ButtonDemo(){
        JFrame jfrm = new JFrame("A Button Example");

        jfrm.setLayout(new FlowLayout());

        jfrm.setSize(220, 90);
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton jbtnUp = new JButton("Up");
        JButton jbtnDown = new JButton("Down");

        jbtnUp.addActionListener(this);
        jbtnDown.addActionListener(this);

        jfrm.add(jbtnUp);
        jfrm.add(jbtnDown);

        JLabel jlab = new JLabel("Press a button.");

        jfrm.add(jlab);
        jfrm.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        if(ae.getActionCommand().equals("Up"))
            jlab.setText("You pressed Up.");
        else
            jlab.setText("You pressed Down.");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ButtonDemo();
            }
        });
    }
}

What is the reason for this exception and how can I solve it?
Regards.

回答1:

Your code is shadowing the variable jlab by re-declaring it in the constructor leaving the class field null. Don't do that and your NPE will go away.

i.e., change this:

ButtonDemo(){
    JFrame jfrm = new JFrame("A Button Example");

    // ...

    // the variable below is being re-declared in the constructor and is thus
    // local to the constructor. It doesn't exist outside this block.
    JLabel jlab = new JLabel("Press a button.");

    // ...
}

to this:

ButtonDemo(){
    JFrame jfrm = new JFrame("A Button Example");

    // ...

    jlab = new JLabel("Press a button."); // note the difference!

    // ...
}

A key to solving NPE's is to carefully inspect the line that is throwing the exception as one variable being used on that line is null. If you know that, you can usually then inspect the rest of your code and find the problem and solve it.



回答2:

jlab in actionPerformed method refers to the JLabel that u've declared outside the constructor ButtonDemo .Which would be null unless u initialize it ( i.e jlab=new JLabel()) .Hence you're getting an Exception .