I am trying to make a checkers game. I created the board already using JButtons. I used JButtons since I thought that would be the easiest way to do it. I'm not entirely sure on how to implement to create the pieces itself. I thought of making the pieces of out JButtons and put one top the squares, but I'm not sure if that would work. I also thought of using JLabels, but I didn't think I could make JLabels clickable. My code for what I have so far. Thanks for the help.
import java.awt.*;
import javax.swing.*;
public class CheckerDemo {
public static void main(String[] args) {
//Creates small menu with two buttons, play and exit
JPanel second = new JPanel();
JPanel panel = new JPanel();
JFrame frame = new JFrame();
//simple message asking user to choose
JLabel hello = new JLabel(" Welcome, please choose.");
//button for exit, closes out panel
JButton exit = new JButton("Exit");
//button to play, goes to the panel with board
JButton play = new JButton("Play!");
//add label and buttons to panel
panel.add(exit);
panel.add(hello);
second.add(play);
//so frame isn't resized, stays small
frame.setResizable(false);
frame.setTitle("Main");
frame.setSize(200,250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//put buttons in certain spots
frame.add(panel, BorderLayout.CENTER);
frame.add(hello, BorderLayout.NORTH);
frame.add(second, BorderLayout.WEST);
//exits the frame on exit button click
exit.addActionListener(e -> {
frame.dispose();
});
//play button goes to the checkerboard, uses checkerboard class
play.addActionListener(e -> {
frame.dispose();
new CheckerBoard();
});
//button sizes
hello.setBounds(10, 20, 80, 50);
exit.setBounds(20,20,50,80);
//set frame to see
frame.setVisible(true);
}
}
CheckerBoard class:
import java.awt.*;
import javax.swing.*;
public class CheckerBoard extends JFrame {
//used to make the board
//creates the frame and panel for the new frame after play clicked
JFrame frame2 = new JFrame();
JPanel panel = new JPanel();
//2d array used for black and white squares
JButton[][] buttons = new JButton[8][8];
//constructor
public CheckerBoard() {
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setSize(750,600);
frame2.setTitle("Checkers");
frame2.setVisible(true);
panel.setSize(500, 500);
JPanel panel = new JPanel(new GridLayout(8,8));
// add squares to the board
for (int i = 1; i < buttons.length; i++) {
for (int j = 1; j < buttons[i].length; j++) {
//creates a new JButton object every time it's looped to add to the panel
buttons[i][j] = new JButton();
//if the 2d array comes across even square( ex -> [2,2]), colors it white
if (i % 2 == j % 2) {
buttons[i][j].setBackground(Color.WHITE);
panel.add(buttons[i][j]);
}
else {
buttons[i][j].setBackground(Color.BLACK);
panel.add(buttons[i][j]);
}
}
}
frame2.add(panel);
panel.setVisible(true);
}
}