JAVA:Swing JButton组件(NullPointerException) [英] JAVA: Swing JButton componnent (NullPointerException)

查看:122
本文介绍了JAVA:Swing JButton组件(NullPointerException)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图显示文本-当您按下一个按钮时显示您按下了按钮".
我得到一个NullPointerException.我已经初始化了类的构造函数中的按钮,并且在初始化之后,我从main()调用了以下方法.

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().

这是代码:

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.

推荐答案

您的代码通过在构造函数中重新声明变量jlab,使class字段为空,从而使变量jlab蒙上阴影.否则,您的NPE将会消失.

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.

即更改此内容

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

    // ...
}

对此:

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

    // ...

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

    // ...
}

解决NPE的关键是仔细检查引发异常的行,因为该行上使用的一个变量为null.如果您知道这一点,通常可以检查其余的代码,找到问题并解决.

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.

这篇关于JAVA:Swing JButton组件(NullPointerException)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆