Tic Tac Toe Game Using Java Swing With Source Code

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:

Get Discount on Top Educational Courses

Brand NameDiscount InformationCoupon Codes Link
Educative.io20% discount on Educative courses and plans
W3Schools20% discount on W3Schools courses
KodeKloud10% discount on KodeKloud courses and plans
GeeksforGeeks30% discount on GeeksforGeeks courses
Target Test Prep20% discount on Target Test Prep
Coding Ninjas₹5000 discount on Coding Ninjas courses
Skillshare40% discount on Skillshare
DataCamp50% discount on DataCamp
365 Data Science57% discount on 365 Data Science Plans
Get SmarterFlat 20% discount on Get Smarter courses
SmartKeedaFlat 40% discount on SmartKeeda courses
StackSocial20% discount on StackSocial courses
				
					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

electronics Store website using html CSS and JavaScript Introduction Hello coders, welcome to another new project. As you know our today’s project …

Digital Marketing Agency website Using HTML, CSS and JavaScript Introduction Hello coders, welcome to another new blog. Today in this project we’ll …

Fruit Slicer Game Using HTML CSS And JavaScript Introduction Hey coders, welcome to another new blog. Today in this blog we’ve created …

Event Organizers Website Using Html Css And JavaScript Introduction Hello coders, welcome to another new blog. As you know that our today’s …

Shape Clicker Game Using HTML CSS And JavaScript Introduction Hey coders, welcome to another new blog. Today in this article we’ve made …

responsive College Website Using Html CSS & JavaScript Introduction Hello coders, welcome to another new blog. Today in this blog post we’ll …