Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement