2013-04-25 82 views
0

我是java的新手,目前通過HeadFirst java book教我自己。 我所經歷的GUI界面,並從書中的代碼似乎並沒有運行,eclipse中的GUI界面異常

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

public class SimpleGui1 implements ActionListener { 


    JButton Button; 

    public static void main(String[] args) { 

     SimpleGui1 gui = new SimpleGui1(); 
     gui.go(); 
    } 

    public void go(){ 

     JFrame frame = new JFrame(); 
     JButton button = new JButton("click me"); 
     button.addActionListener(this); 

     frame.getContentPane().add(button); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(300,300); 
     frame.setVisible(true); 

    } 

    public void actionPerformed (ActionEvent event) { 

     Button.setText("I have been clicked"); 
    } 

} 

The exception : 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196) 
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188) 
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) 

誰能告訴我有什麼不對?

+0

什麼是例外? – Kal 2013-04-25 20:46:33

+0

我猜NullPointerException這裏:** Button.setText(「我已被點擊」); ** – Markus 2013-04-25 20:47:42

回答

5

類成員變量Button從不初始化。而另一個名稱不同(Java區分大小寫)在go方法中本地定義。

ActionListener,你可以簡單地使用ActionEvent源確定Action來源:

public void actionPerformed(ActionEvent event) { 

    JButton button = (JButton) event.getSource(); 
    button.setText("I have been clicked"); 
} 

這消除了需要有JButton作爲類的成員變量。

+0

該死的你快。正確答案+1。 – 2013-04-25 20:49:11

2

初始化按鈕,它仍然爲空。

你有一個NullPointerException。