2011-02-08 82 views
0

我正在嘗試製作一個簡單的GUI,但遇到了一些錯誤。我想創建3個簡單的按鈕,並將它們並排顯示,屏幕的長度。我會如何去做這件事?找不到nullPointerException的源

到目前爲止我的代碼是:

public static void main(String[] args) { 
    JFrame frame = new JFrame ("JFrame"); 
    JPanel panel = new JPanel(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    JButton buttons[] = new JButton[2]; 
    for(int i = 0;i<=buttons.length ; i++){ 
    panel.add(buttons[i]); 
    } 
    frame.getContentPane().add(panel); 
    frame.setSize(500, 500); 
    frame.setVisible(true); 
    } 
+0

你怎麼看,當你通過代碼調試步驟更有用? – 2011-02-08 20:20:33

回答

4

嗯,如果我還記得,在Java對象數組與空引用初始化。所以,在你的工作中,你要爲面板添加null。

你將不得不這樣做:

JButton buttons[] = new JButton[2]; 
for(int i = 0;i < buttons.length ; i++){ 
    buttons[i] = new JButton(/* whatever */); 
    panel.add(buttons[i]); 
} 

話又說回來,這提出了一個問題:爲什麼要使用按鈕的數組,如果你可以加他們爲你創建它們?

2

您需要首先初始化數組中的按鈕。你可以像下面的例子那樣做。

JButton buttons[] = new JButton[2]; 
for(int i = 0; i < buttons.length; i++){ 
    buttons[i] = new JButton("" + i); 
} 
for(int i = 0; i < buttons.length; i++){ 
    panel.add(buttons[i]); 
} 

的問題是,所有的按鈕得到初步初始化爲null。並且組件不允許您向其添加null

2

在將它們添加到面板之前,您需要初始化按鈕。

for(int i = 0;i<buttons.length ; i++){ 
    buttons[i] = new JButton(); 
    panel.add(buttons[i]); 
} 

另外,注意我對做for循環i < buttons.length而不是i <= buttons.length

修改的下面是使用各種Jbutton將(here)一個可愛的小例子。它還包括將ImageIcons添加到按鈕。即錯誤按鈕。

URL imgURL = JButtonDemo.class.getResource("Error.jpg"); 
ImageIcon icon = new createImageIcon(imgURL); // should check that imgURL is not null 
buttons[0] = new JButton("Error!",icon); 

這使得他們一點比默認JButton