2015-08-25 32 views
0

我目前正在阅读一本java书,并且已经就GUI的章节达成了一章。GUI ActionPerformed()创建错误

书已就如何让一个按钮动作事件,我将在下面粘贴示例代码:

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

任何人都可以解释为什么这是行不通的?

+0

你永远不会初始化JButton的'按钮;'。 –

+2

请参阅[什么是堆栈跟踪,以及如何使用它来调试我的应用程序错误?](http://stackoverflow.com/q/3988788/418556)&[什么是空指针异常,以及如何修复它?](http://stackoverflow.com/q/218384/418556) –

+1

全局按钮没有初始化.. go方法中的一个只对该方法范围可见.. –

回答

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