import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Program {
public static void main(String[] args) {
JFrame frame = new JFrame("Demo");
frame.add(new TicTacToePanel(new GridLayout(3,3)));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(5, 5, 200, 200);
frame.setVisible(true);
}
}
class TicTacToe extends JButton {
private boolean isFill;
private int num;
private int row;
private int col;
private String marker;
public TicTacToe(int num,int x,int y) {
this.num=num;
row=y;
col=x;
marker=" ";
setText(marker);
}
public void setMarker(String m) {
marker=m;
setText(marker);
setEnabled(false);
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
}
class TicTacToePanel extends JPanel implements ActionListener {
private void createCell(int num,int x,int y) {
cells[num]=new TicTacToe(num,x,y);
cells[num].addActionListener(this);
add(cells[num]);
}
private TicTacToe[] cells = new TicTacToe[9];
TicTacToePanel(GridLayout layout) {
super(layout);
createCell(0,0,0);
createCell(1,1,0);
createCell(2,2,0);
createCell(3,0,1);
createCell(4,1,1);
createCell(5,2,1);
createCell(6,0,2);
createCell(7,1,2);
createCell(8,2,2);
}
public void actionPerformed(ActionEvent ae) {
for(TicTacToe jb: cells) {
if(ae.getSource()==jb) {
jb.setMarker("X");
}
}
}
}