I am programming in Java and am still rather new. Experimenting with GUI Basics, I decided to make a checkerboard with all 64 cells being instances of JButtons with a filled in background. Sadly, when I tried to compile the code, only two buttons show up and neither of them are colored. I'm trying to understand the problem, but for now it seems a bit beyond me.
package checkerboard;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class Checkerboard extends JFrame {
public Checkerboard() {
JButton black = new JButton("B");
JButton white = new JButton("W");
black.setBackground(Color.BLACK);
white.setBackground(Color.WHITE);
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(8, 8));
p1.setSize(600, 600);
for (int i = 0; i < 8; i++) {
if (i % 2 == 0) {
for (int j = 0; j < 4; j++) {
p1.add(black);
p1.add(white);
}
} else {
for (int j = 0; j < 4; j++) {
p1.add(white);
p1.add(black);
}
}
}
super.add(p1);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Checkerboard frame = new Checkerboard();
frame.setTitle("Checkers");
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
In experimenting with the JPanel, for some strange reason line 27 had a NullPointer Exception.
This is because you are using only one instance object of JButton as a black button, and only one instance object of JButton as a white button, and you are adding the same 2 references to the JPanel p1 more and more. Thus, this won't work and you need to create an object for each button on the board. Here is how you can do such thing:
JButton[] blackButtons = new JButton[4 * 8];
JButton[] whiteButtons = new JButton[4 * 8];
for(int i = 0; i < blackButtons.length; i++)
{
blackButtons[i] = new JButton("B");
blackButtons[i].setBackground(Color.BLACK);
}
for(int i = 0; i < whiteButtons.length; i++)
{
whiteButtons[i] = new JButton("W");
whiteButtons[i].setBackground(Color.WHITE);
}
then you can add them like this:
for (int i = 0; i < 8; i++) {
if (i % 2 == 0) {
for (int j = 0; j < 4; j++) {
p1.add(blackButtons[4 * i + j]);
p1.add(whiteButtons[4 * i + j]);
}
} else {
for (int j = 0; j < 4; j++) {
p1.add(whiteButtons[4 * i + j]);
p1.add(blackButtons[4 * i + j]);
}
}
}
add(p1);