0% found this document useful (0 votes)
22 views1 page

Java Swing Gui

This document contains Java code for a simple Tic Tac Toe game using Swing. It creates a 3x3 grid of buttons for player moves and checks for a winner after each turn. The game alternates between players 'X' and 'O' and displays a message when a player wins.

Uploaded by

fukreedits
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views1 page

Java Swing Gui

This document contains Java code for a simple Tic Tac Toe game using Swing. It creates a 3x3 grid of buttons for player moves and checks for a winner after each turn. The game alternates between players 'X' and 'O' and displays a message when a player wins.

Uploaded by

fukreedits
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import javax.swing.

*;
import java.awt.*;
import java.awt.event.*;

public class TicTacToe extends JFrame {


private JButton[][] buttons = new JButton[3][3];
private char current = 'X';

public TicTacToe() {
setTitle("Tic Tac Toe");
setSize(300, 300);
setLayout(new GridLayout(3, 3));
setDefaultCloseOperation(EXIT_ON_CLOSE);

for (int i = 0; i < 3; i++)


for (int j = 0; j < 3; j++) {
buttons[i][j] = new JButton("");
buttons[i][j].setFont(new Font("Arial", Font.BOLD, 40));
final int r = i, c = j;
buttons[i][j].addActionListener(e -> buttonClick(r, c));
add(buttons[i][j]);
}
}

private void buttonClick(int r, int c) {


if (buttons[r][c].getText().equals("")) {
buttons[r][c].setText(String.valueOf(current));
if (checkWinner(current)) {
JOptionPane.showMessageDialog(this, current + " wins!");
reset();
} else {
current = current == 'X' ? 'O' : 'X';
}
}
}

private boolean checkWinner(char player) {


for (int i = 0; i < 3; i++)
if (buttons[i][0].getText().equals(String.valueOf(player)) &&
buttons[i][1].getText().equals(String.valueOf(player)) &&
buttons[i][2].getText().equals(String.valueOf(player)))
return true;

for (int j = 0; j < 3; j++)


if (buttons[0][j].getText().equals(String.valueOf(player)) &&
buttons[1][j].getText().equals(String.valueOf(player)) &&
buttons[2][j].getText().equals(String.valueOf(player)))
return true;

return buttons[0][0].getText().equals

You might also like