Tic-tac-toe (or Noughts and crosses, Xs and Os) is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three respective marks in a horizontal, vertical, or diagonal row wins the game.
Here is a Java Code for making Tic-tac-toe by the help of JFrame
——————————————————————————————————————–
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TicTacToe extends JFrame implements ActionListener {
private int[][] winCombinations = new int[][] {
{0, 1, 2}, {3, 4, 5}, {6, 7, 8},
{0, 3, 6}, {1, 4, 7}, {2, 5, 8},
{0, 4, 8}, {2, 4, 6}
};
Font f1 = new Font(“Times New Roman”, 1, 72);
JMenuBar bar;
JMenu jm1;
JMenuItem jt1,jt2;
JButton buttons[] = new JButton[9];
int flg = 0;
String letter = “”;
boolean win = false;
public TicTacToe(){
setLayout(new GridLayout(1,1));
bar=new JMenuBar();
jm1=new JMenu(“File”);
jt1=new JMenuItem(“New”);
jt2=new JMenuItem(“Exit”);
add(bar);
jm1.add(jt1);
jm1.addSeparator();
jm1.add(jt2);
add(jm1);
bar.add(jm1);
setVisible(true);
setSize(400,400);
setLayout(new GridLayout(3,3));
for(int i=0; i<=8; i++){
buttons[i] = new JButton();
add(buttons[i]);
buttons[i].addActionListener(this);
}
setVisible(true);
}
public void actionPerformed(ActionEvent a) {
flg++;
if(flg % 2 == 0){
letter = "O";
} else {
letter = "X";
}
JButton pressedButton = (JButton)a.getSource();
pressedButton.setFont(f1);
pressedButton.setBackground(Color.cyan);
pressedButton.setText(letter);
pressedButton.setEnabled(false);
for(int i=0; i<=7; i++){
if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) &&
buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
buttons[winCombinations[i][0]].getText() != ""){
win = true;
}
}
if(win == true){
JOptionPane.showMessageDialog(null, letter + " wins the game!");
System.exit(0);
} else if(flg == 9 && win == false){
JOptionPane.showMessageDialog(null, "The game was tie!");
System.exit(0);
}
}
public static void main(String[] args){
TicTacToe starter = new TicTacToe();
}
}
——————————————————————————————————————–
Result
Download Source Code