I am creating a simple TicTacToe game. I created 9 JButtons by using [3][3] matrix. The thing is that I need to check the state of those buttons so I can determine the winner.
I do not know how can I check / access those button through the if statement without some kind of identifier or index. I could create 9 JButton objects and check them using if statements but it does not seem efficient. I know that this is not the best solution for this game and that I should have created a whole class for the logic of the game, but this way seems very efficient and I really would like to know how to do it this way.
Here is the code:
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.GridLayout;
public class AdinTicTacToe extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 500; //Width of the JFrame
public static final int HEIGHT = 400; //Height of the JFrame
public static void main(String[] args) {
AdinTicTacToe gui = new AdinTicTacToe(3, 3);
gui.setVisible(true);
}
//Creating a matrix of buttons to make flexible layout
JButton[][] buttons = new JButton[3][3];
{
for (int row = 0; row < buttons.length; row++) {
for (int col = 0; col < buttons[0].length; col++) {
JButton cells = new JButton();
buttons[row][col] = cells;
add(cells);
cells.addActionListener(this);
}
}
}
//A constructor to set initial values
public AdinTicTacToe(int rows, int columns) {
super();
setSize(WIDTH, HEIGHT);
setTitle("Tic Tac Toe");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setting a layout
setLayout(new GridLayout(rows, columns));
}
//Handling button clicks
boolean check; //Variable to determine the current state of a button
@Override
public void actionPerformed(ActionEvent e) {
//Using getSource method to avoid multiple if statements and make it efficient
JButton myButton = (JButton) e.getSource();
if (!check)
myButton.setText("X");
; //Set X to the clicked cell
if (check)
myButton.setText("O"); //Set O to the clicked cell
check = !check; //Reverting the button state
myButton.setFont(new Font("Arial", Font.BOLD, 60)); //Set font of X and O
myButton.setEnabled(false); //Disable button after it gets clicked
}
}