GUI ActionPerformed()创建错误

时间:2015-08-25 11:36:22

标签: java swing nullpointerexception awt actionlistener

我目前正在阅读一本java书,我已经到了GUI的一章。

本书给出了如何获取按钮ActionEvent的示例代码,我将在下面粘贴:

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

    //Create a JFrame and add title
    JFrame frame = new JFrame();
    frame.setTitle("Basic GUI");
    //Create a button with text and add an ActionListener
    JButton button = new JButton("CLICK ME");
    button.addActionListener(this);
    //Add the button to the content pane
    frame.getContentPane().add(button);
    //Set JFrame properties
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

}

//What should happen when button is pressed
public void actionPerformed(ActionEvent e) {
        button.setText("Button pressed");
    }
}

然而,当我运行程序并单击按钮时,我收到如下大量错误:(因为帖子上有空格而我缩短了。)

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at SimpleGUI.actionPerformed(SimpleGUI.java:34)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
......

有人可以解释为什么这不起作用吗?

1 个答案:

答案 0 :(得分:0)

NullPointerException由于JButton的全球声明而产生,但它没有在这里初始化尝试这样

public class SimpleGUI implements ActionListener {

JButton button;

public static void main(String[] args) {

    SimpleGUI gui = new SimpleGUI();
    gui.go();

}

private void go() {
    //Create a JFrame and add title
    JFrame frame = new JFrame();
    frame.setTitle("Basic GUI");
    //Create a button with text and add an ActionListener
    button = new JButton("CLICK ME");
    button.addActionListener(this);
    //Add the button to the content pane
    frame.getContentPane().add(button);
    //Set JFrame properties
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent arg0) {
    button.setText("Button Pressed");
}
}
相关问题