简体   繁体   English

JAVA:Swing JButton componnent(NullPointerException)

[英]JAVA: Swing JButton componnent (NullPointerException)

I am trying to show text - "You pressed Button" when you pressed one of buttons. 当我按下其中一个按钮时,我试图显示文本 - “按下按钮”。
I am getting an NullPointerException . 我得到一个NullPointerException I have initialized the buttons inside the constructor of the class and after initialization, I called the following method from main() . 我已经在类的构造函数中初始化了按钮,在初始化之后,我从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. 问候。

Your code is shadowing the variable jlab by re-declaring it in the constructor leaving the class field null. 您的代码通过在构造函数中重新声明它而使类字段为null,从而隐藏变量jlab。 Don't do that and your NPE will go away. 不要这样做,你的NPE会消失。

ie, 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. 解决NPE的关键是仔细检查抛出异常的行,因为该行上使用的一个变量为null。 If you know that, you can usually then inspect the rest of your code and find the problem and solve it. 如果您知道这一点,通常可以检查其余代码并找到问题并解决问题。

jlab in actionPerformed方法是指你在构造函数ButtonDemo之外声明的JLabel。除非你初始化它,否则它将为null(即jlab = new JLabel())。因此你得到了一个例外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM