Hey everyone I am trying to draw a checkerboard in Java with GUI. I have created a square class for the squares of the game board.
Square Class:
import javax.swing.*;
import java.awt.*;
public class Square extends JPanel {
private int width = 80;
private int height = 80;
private int x,y;
private Color color;
public Square(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
public void paint(Graphics graphics){
//setSize(new Dimension(width,height));
graphics.setColor(color);
graphics.drawRect(x,y, width,height);
graphics.fillRect(x,y,width,height);
}
}
Basically I wanted to create a panel with grid layout of 8 by 8. Then add square objects grid layout panel. I want the first row to contain red,black,red,black,red,black,red,black squares and the second row to contain black,red,black,red,black,red,black,red squares.
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(600,600));
JPanel panel = new JPanel(new GridLayout(8,8));
panel.setLayout(new GridLayout(8, 8));
panel.setBackground(Color.green);
Square redsqr1 = new Square(0,0, Color.RED);
Square blksqr1 = new Square(0,0, Color.BLACK);
Square redsqr2 = new Square(0,0, Color.RED);
Square blksqr2 = new Square(0,0, Color.BLACK);
Square redsqr3 = new Square(0,0, Color.RED);
Square blksqr3 = new Square(0,0, Color.BLACK);
Square redsqr4 = new Square(0,0, Color.RED);
Square blksqr4 = new Square(0,0, Color.BLACK);
Square redsqr5 = new Square(0,0, Color.RED);
Square blksqr5 = new Square(0,0, Color.BLACK);
Square redsqr6 = new Square(0,0, Color.RED);
Square blksqr6 = new Square(0,0, Color.BLACK);
Square redsqr7 = new Square(0,0, Color.RED);
Square blksqr7 = new Square(0,0, Color.BLACK);
Square redsqr8 = new Square(0,0, Color.RED);
Square blksqr8 = new Square(0,0, Color.BLACK);
panel.add(redsqr1);
panel.add(blksqr1);
panel.add(redsqr2);
panel.add(blksqr2);
panel.add(redsqr3);
panel.add(blksqr3);
panel.add(redsqr4);
panel.add(blksqr4);
panel.add(blksqr5);
panel.add(redsqr5);
panel.add(blksqr6);
panel.add(redsqr6);
panel.add(blksqr7);
panel.add(redsqr7);
panel.add(blksqr8);
panel.add(redsqr8);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
When I run the program I get the output
Just curious as to why the output is placed in 2 columns with big space between each square. How would i get them to stay side byside on one row to have the first row to containing red,black,red,black,red,black,red,black squares and the second row to containing black,red,black,red,black,red,black,red squares.
Thanks in advance for your help!