2014-01-15 13 views
-3

我做了一個簡單的函數:NullPointerExecption

public class AjouterBouton { 

    public AjouterBouton(int nombre) { 

     JButton[] buttons = new JButton[nombre]; 

     for(int i = 0; i < buttons.length; i++) { 

      buttons[i] = new JButton(); 
      buttons[i].setBackground(Color.LIGHT_GRAY); 
      JPanel pan = Main.grille; 
      pan.add(buttons[i]); 
     } 
    } 
} 

「格柵」 在我的主類的簡單的JPanel:

JPanel grille = new JPanel(); 
int ligne = 6; 
int colone = 5; 
grille.setBounds(6, 117, 980, 314); 
grille.setLayout(new GridLayout(ligne,colone)); 

最後,我加入到這個主類:

new AjouterBouton(72); 

但是,我得到一個JavaNullPointerException

PS:我想這一點,它的工作原理:

final JButton[] buttons = new JButton[72]; 

for(int i = 0; i < buttons.length; i++) { 

    buttons[i] = new JButton(); 
    buttons[i].setBackground(Color.LIGHT_GRAY); 
    grille.add(buttons[i]); 
} 

但我想用方法來添加我的按鈕。我是初學者;有人能幫我嗎?

+3

總是與你的問題,這表明其中拋出錯誤的行添加堆棧跟蹤。 –

+2

請擺脫「卡住2小時」位。這怎麼幫助我們找出你的問題?它與問題有什麼關係 - 沒有。問這樣的問題的關鍵在於包含與問題有關的相關信息,例如堆棧跟蹤和導致該問題的行,並排除不相關的位,這些只會分散注意力。 –

+1

@HovercraftFullOfEels和我們知道的標籤是'JAVA' – nachokk

回答

1

傳遞JPanel的參考,你的構造方法:

public AjouterBouton(int nombre, JPanel pan) 
{ 
    JButton[] buttons = new JButton[nombre]; 

    for(int i = 0; i < buttons.length; i++) 
    { 
     buttons[i] = new JButton(); 
     buttons[i].setBackground(Color.LIGHT_GRAY); 
     //JPanel pan = Main.grille; 
     pan.add(buttons[i]); 
    } 
} 

在主營:

int ligne = 6; 
int colone = 5; 

JPanel grille = new JPanel(); 
grille.setBounds(6, 117, 980, 314); 
grille.setLayout(new GridLayout(ligne,colone)); 
// this could be just a static method call: AddButtonsToPanel() 
// doesn't need to be an object 
AjouterBouton button = new AjouterBouton(72, grille); 
+0

非常感謝! :D它的工作! – Clyx

0
JPanel pan = Main.grille; 

這行代碼在AjouterBouton方法for循環中調用。它在方法存在時被處置。

如果沒有看到堆棧軌跡,我不得不邊走邊看,並說你得到了NullPointerException,因爲你試圖在面板沒有正確實例化的時候添加pan

+0

現在我遇到了其他問題,我得到了ArrayIndexOufOfBoundsExecption。在我的方法中:new AjouterBouton(3);我得到這個錯誤..你能幫我嗎? – Clyx

+0

當然,使用代碼和堆棧跟蹤發佈另一個問題,我很樂意幫助 – Taegost