簡體   English   中英

為什么會出現NullPointerException錯誤?

[英]Why do I get a NullPointerException error?

這是我的代碼...

 import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;

public class test extends JFrame {
    public test() {     
        setSize(1000,600);
    }

    private static JButton[] remove;
    private static JPanel p = new JPanel();

    public static void main(String[]args){
        JFrame t = new test();
        remove = new JButton[25];
        for (int i = 0; i < 25; i++) { 
            remove[i].setBounds(243, 92 + 30 * i, 85, 20);
        }
    t.setVisible(true);
    }

} 

我創建了一個由25個按鈕組成的數組,但是為什么它仍然拋出此錯誤:S?

在您的行中:

remove = new JButton[25];

您正在為JButton對象創建一個具有25個插槽的數組。 現在,您必須創建要放置到數組中的每個JButton。

for(int i= 0; i < 25; i++) {
   remove[i] = new JButton();
}

之后,當您嘗試訪問數組元素時,將直接訪問以前創建的JButton之一。

在此之前,您創建的數組僅包含null元素,並且當您嘗試訪問一個數組插槽時,就好像您試圖讓null引用執行某項操作一樣,這是不可能的,這就是為什么您會得到NullPointerException

使用remove = new JButton[25]您可以創建具有25個項目容量的buttons-array ,但是您的數組為空。 因此,您必須先創建新的Button ,然后才能為每個Button設置setBounds(243, 92 + 30 * i, 85, 20)

remove = new JButton[25];
for(int i=0;i<25;i++){
   remove[i] = new JButton();
   remove[i].setBounds(243,92+30*i,85,20);
}

所有未初始化為指向堆上對象的引用都設置為等於null。

嘗試這個:

    // Ever heard of "magic numbers"?  These are very bad, indeed.
    // Your snippet is loaded with them.
    remove = new JButton[25];
    for(int i=0;i<25;i++){
        remove[i] = new JButton();
        remove[i].setBounds(243,92+30*i,85,20);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM