import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class TicTacToe extends JPanel implements ActionListener {
JButton btnButton1, btnButton2, btnButton3, btnButton4, btnButton5, btnButton6, btnButton7,btnButton8, btnButton9;
JPanel panel1, panel2, panel3;
JTextField txtMove=new JTextField(10);
int turn =1; // 1 is O 2 X
int cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8, cell9;
public TicTacToe() {
setLayout(new GridLayout(3,3));
panel1= new JPanel();
panel2= new JPanel();
panel3= new JPanel();
panel1.setLayout(new GridLayout(3,3));
cell1=cell2=cell3=cell4=cell5=cell6=cell7=cell8=cell9=0;
btnButton1=new JButton(" ");
btnButton2=new JButton(" ");
btnButton3=new JButton(" ");
btnButton4=new JButton(" ");
btnButton5=new JButton(" ");
btnButton6=new JButton(" ");
btnButton7=new JButton(" ");
btnButton8=new JButton(" ");
btnButton9=new JButton(" ");
btnButton1.setActionCommand("cell1");
btnButton2.setActionCommand("cell2");
btnButton3.setActionCommand("cell3");
btnButton4.setActionCommand("cell4");
btnButton5.setActionCommand("cell5");
btnButton6.setActionCommand("cell6");
btnButton7.setActionCommand("cell7");
btnButton8.setActionCommand("cell8");
btnButton9.setActionCommand("cell9");
btnButton1.addActionListener(this);
btnButton2.addActionListener(this);
btnButton3.addActionListener(this);
btnButton4.addActionListener(this);
btnButton5.addActionListener(this);
btnButton6.addActionListener(this);
btnButton7.addActionListener(this);
btnButton8.addActionListener(this);
btnButton9.addActionListener(this);
panel1.add(btnButton1);
panel1.add(btnButton2);
panel1.add(btnButton3);
panel1.add(btnButton4);
panel1.add(btnButton5);
panel1.add(btnButton6);
panel1.add(btnButton7);
panel1.add(btnButton8);
panel1.add(btnButton9);
panel3.add(txtMove);
add(panel1);
add(panel2);
add(panel3);
setPreferredSize(new Dimension(300,300));
}
public void actionPerformed(ActionEvent event) {
System.out.println(event.getActionCommand());
String s=event.getActionCommand();
String txtCaption=" ";
if(turn==1) txtCaption="O";
else
if(turn==2) txtCaption="X";
if(s=="cell1" && cell1==0) {
btnButton1.setText(txtCaption);
cell1=turn;
}
if(s=="cell2" && cell2==0) {
btnButton2.setText(txtCaption);
cell2=turn;
}
if(s=="cell3" && cell3==0) {
btnButton3.setText(txtCaption);
cell3=turn;
}
if(s=="cell4" && cell4==0) {
btnButton4.setText(txtCaption);
cell4=turn;
}
if(s=="cell5" && cell5==0) {
btnButton5.setText(txtCaption);
cell5=turn;
}
if(s=="cell6" && cell6==0) {
btnButton6.setText(txtCaption);
cell6=turn;
}
if(s=="cell7" && cell7==0) {
btnButton7.setText(txtCaption);
cell7=turn;
}
if(s=="cell8" && cell8==0) {
btnButton8.setText(txtCaption);
cell8=turn;
}
if(s=="cell9" && cell9==0) {
btnButton9.setText(txtCaption);
cell9=turn;
}
if(turn==1) turn=2;
else
if(turn==2) turn=1;
}
}
*Edited: topic title renamed to be more meaninful
This post has been edited by pbl: 29 April 2012 - 09:58 AM

New Topic/Question
Reply



MultiQuote



|