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