简体   繁体   中英

Why do I get a NullPointerException error?

Here is my code...

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

} 

I created an array that consists of 25 buttons but why is it still throwing this error :S?

In your line:

remove = new JButton[25];

Your are creating an array with 25 slots for JButton objects. You must now create every JButton you want to place into the array.

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

After that, when you attempt to access an array element, you will be accessing one of your previously created JButtons directly.

Before that, your created array contains only null elements and when you try to access one of your array slots it is as if you were trying to ask a null reference to do something, which is not possible and that's why you get a NullPointerException .

with this remove = new JButton[25] you just create buttons-array with 25 items capacity but your array is empty. so you have to first create new Button and then you can set setBounds(243, 92 + 30 * i, 85, 20) for each.

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

All references that are not initialized to point to an object on the heap are set equal to null.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM