-3

solution

So i was trying to do a java-swing-gui for a school project and therefor I have to add 72 Buttons (idk) to a JPanel element. I tried using a for-loop:

for (JButton btn : btns) {
    panel.add(btn);
}

but it didnt really work out and threw a nullPointerExeption. Any suggestions?

Here is the full code:

import javax.swing.*;
import javax.swing.plaf.DimensionUIResource;

import java.awt.*;

public class mädn extends JFrame{
    static JPanel panel = new JPanel();
    static JFrame frame = new JFrame();
    static JButton[] fields = new JButton[72];

    public static void main(String[] args) {
        new mädn();
    }

    public mädn() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(new DimensionUIResource(500, 500));
        frame.setTitle("Mensch Ärger Dich Nicht");

        panel.setLayout(new GridLayout(11, 11));
        panel.setBackground(Color.blue);
        
        for (JButton field : fields) {
            field.setSize(20, 20);
            panel.add(field);
        }

        frame.add(panel);
        frame.setVisible(true);
    }
}

Jonas
  • 52
  • 1
  • 8
  • 2
    You haven’t initialised the contents of the array – MadProgrammer Mar 21 '22 at 19:16
  • When creating an object array, the contents of the array is initially set to `null` (each element), you need to fill the array with values before you can use them. You can use a loop to create each element and populate the panel. Also, `setSize`, in this context, isn't going to do anything – MadProgrammer Mar 21 '22 at 19:32

1 Answers1

1

When you create an array like this:

static JButton[] fields = new JButton[72];

that array is empty. In other words, even though that array has the capacity to keep 72 buttons, it doesn't have those buttons yet, you have to add them manually, like this:

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

But if you don't, fields[i] will be null by default, and so when you try to do field.setSize(20, 20), that field is null and will cause a NullPointerException.

Primitive arrays also have default values. For example elements of an array of int are all 0, and elements of an array of boolean are all false. The same is true for non-primitive arrays (like JButton), the elements are all by default null.

Your final code would look something like this:

for (int i = 0; i < 72; i++) {
    fields[i] = new JButton();
    fields[i].setSize(20, 20);
    panel.add(fields[i]);
}

or:

for (int i = 0; i < 72; i++) {
    JButton field = new JButton();
    fields[i] = field;
    field.setSize(20, 20);
    panel.add(field);
}

or even shorter:

for (int i = 0; i < 72; i++) {
    var field = fields[i] = new JButton();
    field.setSize(20, 20);
    panel.add(field);
}

Also consider turning that 72 into a constant (a static final field).

SMMH
  • 310
  • 1
  • 13