【问题标题】:Java GUI programmmingJava GUI 编程
【发布时间】:2012-06-04 19:43:43
【问题描述】:

代码给出了空指针异常的错误.....要做什么?

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

public class Gui implements ActionListener{
JButton button;

public Gui(){
    JFrame frame=new JFrame();
    JButton button =new JButton("click me!");
    button.addActionListener(this);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(button);
    frame.setSize(270,300);
    frame.setVisible(true);
}
public static void main(String[] args){
    new Gui();
}

public void actionPerformed(ActionEvent e){
    button.setText("I've been clicked");
}

}

【问题讨论】:

  • 我认为在尝试 GUI 开发之前,您需要了解更多有关 Java 的知识。
  • 另见Initial Threads

标签: java swing nullpointerexception scope


【解决方案1】:
JButton button =new JButton

这会创建一个本地变量。
button 字段仍然是 null

【讨论】:

    【解决方案2】:

    您在 actionPerformed 方法中引用的字段 button 从未初始化,因此为空。

    您在 main 方法中添加了这个按钮 JButton button =new JButton("click me!");,但您的 actionPerformed 从未意识到这一点。

    改行改为阅读

    this.button =new JButton("click me!");

    【讨论】:

      【解决方案3】:

      您的问题是该按钮仅在构造函数中可见。

      【讨论】:

        猜你喜欢
        • 2015-09-11
        • 2013-03-15
        • 2012-09-13
        • 2014-08-24
        • 2011-11-07
        • 1970-01-01
        • 2012-05-28
        • 2010-10-20
        • 1970-01-01
        相关资源
        最近更新 更多