Tic Tac Toe Game Using Java Swing

Tic Tac Toe Game Using Java Swing

Introduction:

In this article, we will demonstrate how to build Tic Tac Toe Game using Java Swing library. This Tic Tac Toe Game allows you to Play a game easily using a graphical user interface (GUI) application. This game is develop with the Java Swing library which offers a set of components that can be use to build a Graphical user interface(GUI). This game has an easy and simple design with buttons to play the game. So grab a seat, pour a cup of coffee and start playing Tic Tac Toe Game.

Explanation:

This Tic Tac Toe Game is a Graphical user interface(GUI) Game that allows user to easily Play the game using buttons. Users may very quickly play the Game using the system simple design. The Tic Tac Toe Game has simple design with buttons. The player can click on the button one by one to play the game.

The users may play the game using buttons. This game can be played by 2 users. The 1st player can click on any button the value of the button will be ‘x’.  When the 2nd player clicks the button the value of button will be ‘o’.  The winner of the game is decided based on the rows, column or diagonal values should be same.

The Java Swing library which provides flexible set of components is used to build the Tic Tac Toe Game. The application makes use of Swing components such as Jbutton, JPanel and JFrame among many other Swing components. Button event is handled by the ActionListener interface and button events are defined using ActionListener’s actionPerformed() method. The winner of the game is checked using checkForWinner() method.

Methods used in the project:

actionPerformed():

The action or events of the buttons are handled using this method. Buttons in the system to generate the value of button is handled using this method. This method describes how the component should behave after the button is click.

 

checkForWinner():

This is a user defined method to check the winner of game. To win the game the any one player needs the value of row, column or diagonal should be same. If values of row, column or diagonal is not same it pop ups the dialog box with ‘tie’ message.

 

resetGame():

This is a user defined method to reset the game when the winner of game is declared. The value of buttons are assigned to null when this method is triggered.

Source Code:

 
				
					import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class tic_tac_toe implements ActionListener {
    private JFrame frame;
    private JPanel panel;
    private JButton[] buttons = new JButton[9];
    private boolean xTurn = true;

    public tic_tac_toe() {
        frame = new JFrame("Tic-Tac-Toe");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new JPanel();
        panel.setLayout(new GridLayout(3, 3));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        for (int i = 0; i < 9; i++) {
            buttons[i] = new JButton();
            buttons[i].setFont(new Font("Arial", Font.PLAIN, 40));
            buttons[i].addActionListener(this);
            panel.add(buttons[i]);
        }

        frame.add(panel, BorderLayout.CENTER);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        JButton button = (JButton) e.getSource();
        if (xTurn) {
            button.setText("X");
        } else {
            button.setText("O");
        }
        button.setEnabled(false);
        xTurn = !xTurn;

        checkForWinner();
    }

    public void checkForWinner() {
        // Check rows
        for (int i = 0; i < 9; i += 3) {
            if (buttons[i].getText().equals(buttons[i+1].getText()) && buttons[i].getText().equals(buttons[i+2].getText()) && !buttons[i].isEnabled()) {
                JOptionPane.showMessageDialog(frame, buttons[i].getText() + " wins!");
                resetGame();
                return;
            }
        }

        // Check columns
        for (int i = 0; i < 3; i++) {
            if (buttons[i].getText().equals(buttons[i+3].getText()) && buttons[i].getText().equals(buttons[i+6].getText()) && !buttons[i].isEnabled()) {
                JOptionPane.showMessageDialog(frame, buttons[i].getText() + " wins!");
                resetGame();
                return;
            }
        }

        // Check diagonals
        if (buttons[0].getText().equals(buttons[4].getText()) && buttons[0].getText().equals(buttons[8].getText()) && !buttons[0].isEnabled()) {
            JOptionPane.showMessageDialog(frame, buttons[0].getText() + " wins!");
            resetGame();
            return;
        }
        if (buttons[2].getText().equals(buttons[4].getText()) && buttons[2].getText().equals(buttons[6].getText()) && !buttons[2].isEnabled()) {
            JOptionPane.showMessageDialog(frame, buttons[2].getText() + " wins!");
            resetGame();
            return;
        }

        // Check for tie
        boolean tie = true;
        for (int i = 0; i < 9; i++) {
            if (buttons[i].isEnabled()) {
                tie = false;
                break;
            }
        }
        if (tie) {
            JOptionPane.showMessageDialog(frame, "Tie game!");
            resetGame();
        }
    }

    public void resetGame() {
        for (int i = 0; i < 9; i++) {
            buttons[i].setText("");
            buttons[i].setEnabled(true);
        }
        xTurn = true;
    }

    public static void main(String[] args) {
        new tic_tac_toe();
    }
}
				
			

Output:

Find More Projects

Hostel Management System Using Python With Source Code by using Python Graphical User Interface GUI Introduction: Managing a hostel efficiently can be …

Contra Game Using Python with source code using Pygame Introduction: Remember the super fun Contra game where you fight aliens and jump …

Restaurant Billing Management System Using Python with Tkinter (Graphical User Interface) Introduction: In the bustling world of restaurants, efficiency is paramount, especially …

Jungle Dash Game Using Python with source code with pygame module Introduction: Dive into the excitement of jungle adventures with our new …

Building a Tetris Game with Python with source code Introduction: Welcome to the world of Tetris, where falling blocks meet strategic maneuvers …

Super Mario Game Using Python with source code Introduction: Remember playing Super Mario as a kid? It’s that classic game where you …

All Coding Handwritten Notes

Browse Handwritten Notes