Gui tris (tic tac toe)

Hi,
i am trying to create the tris game in java (maybe you know this game as tic tac toe). I created windows and the alghoritm to play. But now i have the problem to create the board. My idea is to create a board with nine clickable cells, the player clicks on the cell he wants (if it's free), then the computer plays and so on...but i don't have the knowledges of making complex graphic things in java. How can I do?

ok, and how can i manage the player's click?MouseListener on the JLabel.
remember
also that when the player clicks, the program must
draw a symbol (x or o depending from the choice of
player). how can i do all this things? For a noob
like me this is very difficultRead the tutorials. I'm not going to explain to you how to create your app if you can read it up yourself.

Similar Messages

  • Get blank screen each time? tic tac toe GUI...

    I get a blank screen each time i run this...I'm trying to display a tic tac toe board...the x's and o's are randomly generated...any idea why it's blank each time??
    public class TicTacToe extends JFrame
         private ImageIcon x = new ImageIcon("cross.gif");
         private ImageIcon o = new ImageIcon("not.gif");
         Random random = new Random(2);
         public TicTacToe()
              setLayout(new GridLayout(3,3));
              for(int y = 0; y<= 9; y++)
                Random r = new Random(2);
                   int randint = r.nextInt();
                   if (randint == 0)
                        add(new JLabel(x));
                   if (randint == 2)
                        add(new JLabel(o));
         public static void main(String args[])
              TicTacToe frame = new TicTacToe();
              frame.setTitle("Tic Tac Toe");
              frame.setSize(450,450);
              frame.setLocationRelativeTo(null);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
    }

    Timm017 wrote:
    Interested, what was wrong?He used Random and random.nextInt() incorrectly. Given that nextInt() without arguments can return any int between Integer.MIN_VALUE and Integer.MAX_VALUE with equal probability, the chance of hitting 0 or 2 is fairly low. So, most times (for most Random seeds), his code would never add any buttons to the panel. And, actually, since he used a '2' to seed the Random generator, he always got the same sequence of "random" numbers every time. So, his code would always give the same 9 numbers, and, apparently, those numbers don't include either 0 or 2.
    By the way, rollarace, besides picking the proper nextInt(...) method [you want the one that requires a parameter, as I assume you figured out], you should create the Random object once BEFORE the loop starts, and then just reuse it.
    Also:
    for(int y = 0; y<= 9; y++)should be:
    for(int y = 0; y< 9; y++)Otherwise, once the nextInt(...) part was fixed, he'd add 10 buttons.

  • Creating Tic Tac Toe GUI game.

    Okay so can someone please help fix my code for Tic Tac Toe i have no idea how to! =/
    I'm new to programming so help would be appreciated..
    thanx.
    <code>
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TicTacToe implements ActionListener {
    /*Instance Variables*/
    private JFrame window = new JFrame("Tic-Tac-Toe");
    private JButton button1 = new JButton("");
    private JButton button2 = new JButton("");
    private JButton button3 = new JButton("");
    private JButton button4 = new JButton("");
    private JButton button5 = new JButton("");
    private JButton button6 = new JButton("");
    private JButton button7 = new JButton("");
    private JButton button8 = new JButton("");
    private JButton button9 = new JButton("");
    private String letter = "";
    private ImageIcon O = new ImageIcon("LET-O.jpg");
    private ImageIcon X = new ImageIcon("LET-X.jpg");
    private int count = 0;
    private boolean win = false;
    public TicTacToe(){
    /*Create Window*/
    window.setSize(300,300);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setLayout(new GridLayout(3,3));
    /*Add Buttons To The Window*/
    window.add(button1);
    window.add(button2);
    window.add(button3);
    window.add(button4);
    window.add(button5);
    window.add(button6);
    window.add(button7);
    window.add(button8);
    window.add(button9);
    /*Add The Action Listener To The Buttons*/
    button1.addActionListener(this);
    button2.addActionListener(this);
    button3.addActionListener(this);
    button4.addActionListener(this);
    button5.addActionListener(this);
    button6.addActionListener(this);
    button7.addActionListener(this);
    button8.addActionListener(this);
    button9.addActionListener(this);
    /*Make The Window Visible*/
    window.setVisible(true);
    public void actionPerformed(ActionEvent e) {
    count++;
    /*Calculate Who's Turn It Is*/
    if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9)
         X = new ImageIcon("LET-X.jpg");
    else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
         O = new ImageIcon("LET-O.jpg");
    /*Display X's or O's on the buttons*/
    if(e.getSource() == button1){
    button1.setIcon();
    button1.setEnabled(false);
    } else if(e.getSource() == button2){
    button2.setIcon();
    button2.setEnabled(false);
    } else if(e.getSource() == button3){
    button3.setIcon();
    button3.setEnabled(false);
    } else if(e.getSource() == button4){
    button4.setIcon();
    button4.setEnabled(false);
    } else if(e.getSource() == button5){
    button5.setIcon();
    button5.setEnabled(false);
    } else if(e.getSource() == button6){
    button6.setIcon();
    button6.setEnabled(false);
    } else if(e.getSource() == button7){
    button7.setIcon();
    button7.setEnabled(false);
    } else if(e.getSource() == button8){
    button8.setIcon();
    button8.setEnabled(false);
    } else if(e.getSource() == button9){
    button9.setIcon();
    button9.setEnabled(false);
    //Determine who won
    //horizontal wins
    if( button1.getText() == button2.getText() && button2.getText() == button3.getText() && button1.getText() != ""){
    win = true;
    else if(button4.getText() == button5.getText() && button5.getText() == button6.getText() && button4.getText() != ""){
    win = true;
    else if(button7.getText() == button8.getText() && button8.getText() == button9.getText() && button7.getText() != ""){
    win = true;
    //vertical wins
    else if(button1.getText() == button4.getText() && button4.getText() == button7.getText() && button1.getText() != ""){
    win = true;
    else if(button2.getText() == button5.getText() && button5.getText() == button8.getText() && button2.getText() != ""){
    win = true;
    else if(button3.getText() == button6.getText() && button6.getText() == button9.getText() && button3.getText() != ""){
    win = true;
    //diagonal wins
    else if(button1.getText() == button5.getText() && button5.getText() == button9.getText() && button1.getText() != ""){
    win = true;
    else if(button3.getText() == button5.getText() && button5.getText() == button7.getText() && button3.getText() != ""){
    win = true;
    else {
    win = false;
    /*Show a dialog if someone wins or the game is tie*/
    if(win == true)
    JOptionPane.showMessageDialog(null, letter + " WINS!");
    else if(count == 9 && win == false)
    JOptionPane.showMessageDialog(null, "Tie Game!");
    public static void main(String[] args)
    new TicTacToe();
    </code>

    Yeah Thanks.
    So I'm just stuck here. Like I need to program a Tic Tac Toe GUI with the X's and O's as images but I have no clue on what to do next. I have the images for both but I don't know how to make them work once the buttons are clicked.
    Sorry here it is again..
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TicTacToe implements ActionListener {
    /*Instance Variables*/
    private JFrame window = new JFrame("Tic-Tac-Toe");
    private JButton button1 = new JButton("");
    private JButton button2 = new JButton("");
    private JButton button3 = new JButton("");
    private JButton button4 = new JButton("");
    private JButton button5 = new JButton("");
    private JButton button6 = new JButton("");
    private JButton button7 = new JButton("");
    private JButton button8 = new JButton("");
    private JButton button9 = new JButton("");
    private String letter = "";
    private ImageIcon O = new ImageIcon("LET-O.jpg");
    private ImageIcon X = new ImageIcon("LET-X.jpg");
    private int count = 0;
    private boolean win = false;
    public TicTacToe(){
    /*Create Window*/
    window.setSize(300,300);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setLayout(new GridLayout(3,3));
    /*Add Buttons To The Window*/
    window.add(button1);
    window.add(button2);
    window.add(button3);
    window.add(button4);
    window.add(button5);
    window.add(button6);
    window.add(button7);
    window.add(button8);
    window.add(button9);
    /*Add The Action Listener To The Buttons*/
    button1.addActionListener(this);
    button2.addActionListener(this);
    button3.addActionListener(this);
    button4.addActionListener(this);
    button5.addActionListener(this);
    button6.addActionListener(this);
    button7.addActionListener(this);
    button8.addActionListener(this);
    button9.addActionListener(this);
    /*Make The Window Visible*/
    window.setVisible(true);
    public void actionPerformed(ActionEvent e) {
    count++;
    /*Calculate Who's Turn It Is*/
    if(count == 1 || count == 3 || count == 5 || count == 7 || count == 9)
    X = new ImageIcon("LET-X.jpg");
    else if(count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
    O = new ImageIcon("LET-O.jpg");
    /*Display X's or O's on the buttons*/
    if(e.getSource() == button1){
    button1.setIcon();
    button1.setEnabled(false);
    } else if(e.getSource() == button2){
    button2.setIcon();
    button2.setEnabled(false);
    } else if(e.getSource() == button3){
    button3.setIcon();
    button3.setEnabled(false);
    } else if(e.getSource() == button4){
    button4.setIcon();
    button4.setEnabled(false);
    } else if(e.getSource() == button5){
    button5.setIcon();
    button5.setEnabled(false);
    } else if(e.getSource() == button6){
    button6.setIcon();
    button6.setEnabled(false);
    } else if(e.getSource() == button7){
    button7.setIcon();
    button7.setEnabled(false);
    } else if(e.getSource() == button8){
    button8.setIcon();
    button8.setEnabled(false);
    } else if(e.getSource() == button9){
    button9.setIcon();
    button9.setEnabled(false);
    //Determine who won
    //horizontal wins
    if( button1.getText() == button2.getText() && button2.getText() == button3.getText() && button1.getText() != ""){
    win = true;
    else if(button4.getText() == button5.getText() && button5.getText() == button6.getText() && button4.getText() != ""){
    win = true;
    else if(button7.getText() == button8.getText() && button8.getText() == button9.getText() && button7.getText() != ""){
    win = true;
    //vertical wins
    else if(button1.getText() == button4.getText() && button4.getText() == button7.getText() && button1.getText() != ""){
    win = true;
    else if(button2.getText() == button5.getText() && button5.getText() == button8.getText() && button2.getText() != ""){
    win = true;
    else if(button3.getText() == button6.getText() && button6.getText() == button9.getText() && button3.getText() != ""){
    win = true;
    //diagonal wins
    else if(button1.getText() == button5.getText() && button5.getText() == button9.getText() && button1.getText() != ""){
    win = true;
    else if(button3.getText() == button5.getText() && button5.getText() == button7.getText() && button3.getText() != ""){
    win = true;
    else {
    win = false;
    /*Show a dialog if someone wins or the game is tie*/
    if(win == true)
    JOptionPane.showMessageDialog(null, letter + " WINS!");
    else if(count == 9 && win == false)
    JOptionPane.showMessageDialog(null, "Tie Game!");
    public static void main(String[] args)
    new TicTacToe();
    }

  • Tic Tac Toe with simple GUI

    Hello,
    I am working on a Tic Tac Toe game, I have already started woking on it put i am
    stuck on the array part. This is what is required in the project: Create a nine-member array to hold results of the game.. Initialize the array before the start of the game...Allow the user input to indicate which square ther user selects...
    Thank You
    help will be appreciated..
    import javax.swing.JOptionPane;
    import java.awt.*;
    import java.applet.*;
    public class TicTacToe extends Applet
    public void init()
    // declaration aand created array
    int Array[];
    Array = new int[8];
    String input1;
    String input2;
    int choice1;
    int choice2;
    input1 =
    JOptionPane.showInputDialog
    "Please select your symbol\n"+
    "1= O \n"+
    "2= X \n");
    // converts string to integer
    choice1 = Integer.parseInt( input1 );
    // draws the TicTacToe Board...
    public void paint (Graphics g)
         Dimension d = getSize();
         g.setColor(Color.blue);
    int X_coordinate = d.width / 3;
         int Y_coordinate = d.height / 3;
         g.drawLine(X_coordinate, 0, X_coordinate, d.height);      
         g.drawLine(2*X_coordinate, 0, 2*X_coordinate, d.height);
         g.drawLine(0, Y_coordinate, d.width, Y_coordinate);
         g.drawLine(0, 2*Y_coordinate, d.width, 2*Y_coordinate);
    } //end of paitn method
    }// end of class

    Try this:
    import javax.swing.*;
    import java.awt.*;
    import java.applet.*;
    public class TicTac extends JApplet
    public void init()
    // declaration aand created array
         int Array[] = new int[8];
         String input1;
         String input2;
         int    choice1 = 0;
         int    choice2;
         for(int i=0; i < Array.length; i++) Array[i] = 0;
         while (choice1 == 0)
              input1 = JOptionPane.showInputDialog
                   ("Please select your symbol\n"+
                    "1= O \n"+
                    "2= X \n");
              if (input1.equals("1")) choice1 = 1;
              if (input1.equals("2")) choice1 = 2;
    //     converts string to integer
    //     choice1 = Integer.parseInt( input1 );
    // draws the TicTacToe Board...
    public void paint(Graphics g)
         Dimension d = getSize();
         g.setColor(Color.blue);
         int sz = 0;
         if (d.height/4 - 10 < d.width/4) sz = d.height / 4;
              else             sz = d.width  / 4;
         for (int j=0; j < 4; j++)
              g.drawLine(10,sz*j+10,sz*3+10,sz*j+10);
              g.drawLine(j*sz+10,10,j*sz+10,sz*3+10);
         g.setColor(Color.black);
         g.drawRect(9,9,sz*3+2,sz*3+2);
    } //end of paitn method
    }// end of class
    Noah
    import javax.swing.*;
    import java.awt.*;
    import java.applet.*;
    public class TicTac extends JApplet
    public void init()
    // declaration aand created array
         int Array[] = new int[8];
         String input1;
         String input2;
         int choice1 = 0;
         int choice2;
         for(int j=0; j < Array.length; j++) Array[j] = 0;
         while (choice1 == 0)
              input1 = JOptionPane.showInputDialog
                   ("Please select your symbol\n"+
                   "1= O \n"+
                   "2= X \n");
              if (input1.equals("1")) choice1 = 1;
              if (input1.equals("2")) choice1 = 2;
    //     converts string to integer
    //     choice1 = Integer.parseInt( input1 );
    // draws the TicTacToe Board...
    public void paint(Graphics g)
         Dimension d = getSize();
         g.setColor(Color.blue);
         int sz = 0;
         if (d.height/4 - 10 < d.width/4) sz = d.height / 4;
              else                         sz = d.width / 4;
         for (int j=0; j < 4; j++)
              g.drawLine(10,sz*j+10,sz*3+10,sz*j+10);
              g.drawLine(j*sz+10,10,j*sz+10,sz*3+10);
         g.setColor(Color.black);
         g.drawRect(9,9,sz*3+2,sz*3+2);
    } //end of paitn method
    }// end of class

  • Basic Tic Tac Toe programming help please

    I'm trying to make a seperate java class(there is another main that calls this using SWING interface) that makes mark on the board.
    It's supposed to do the following
    Method makeMark returns:
    a null if the cell indicated by row and column has already been marked
    an X if it is X's turn (X gets to go first)
    a Y if it is Y's turn
    Thus makeMark will have to keep of marks made previously and return the appropriate string
    for the requested cell.
    and here is what I got so far, but only getting empty clicks as a respond. Any help will be appreciated. thanks.
    import javax.swing.JButton;
    public class TicTacToeGame {
         public String makeMark(int row, int column){
    String player = "X";
    String [][] Enum = new String [3][3];
              for (row=0; row<=2; row++){
                   for (column=0; column<=2; column++)
                        if (Enum[row][column] == "")
    if (player == "X"){
    Enum[row][column] = "X";
    player = "Y";
    return "X";
    if (player == "Y"){
    Enum[row][column] = "O";
    player = "X";
    return "Y";
    else
    return null;
              return player;
    }

    ok is there a simpler codes that will just flip-flop between X and O? I had it working before but somehow it's not working anymore. Before I had
    public String makeMark(int row, int column){
    player = "X";
    if (player = "X")
    player = "O";
    else if (player = "O")
    player = "X";
    or soemthing like this but it used to work, but I had to revise the code to do more things and it stopped even flip-flopping between X and O.
    Here's main code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * This class is the GUI for TicTacToe. It only handles user clicks on
    * buttons, which represent X's and O's
    * @author Hal Mendoza
    * CSE 21 - Jan 18, 2011, 8:18:22 PM
    * TicTacToe.java
    public class TicTacToe extends JPanel implements ActionListener {
    public final static int NUM_ROWS_COLUMNS = 3;
    private JButton arrayofButtons[][] = new JButton[NUM_ROWS_COLUMNS][NUM_ROWS_COLUMNS];
    TicTacToeGame board = new TicTacToeGame();
    public TicTacToe() {
         BoxLayout ourLayout = new BoxLayout(this, BoxLayout.Y_AXIS);
         setLayout(ourLayout);
         add(buildMainPanel());
    * Builds the panel with buttons
    * @return the panel with buttons
    private JPanel buildMainPanel() {
         JPanel panel = new JPanel();
         GridLayout gridLayout = new GridLayout(0, NUM_ROWS_COLUMNS);
         panel.setLayout(gridLayout);
         for (int row = 0; row < arrayofButtons.length; ++row)
              for (int column = 0; column < arrayofButtons[0].length; ++column) {
                   arrayofButtons[row][column] = new JButton();
                   arrayofButtons[row][column].setPreferredSize(new Dimension(50, 50));
                   arrayofButtons[row][column].addActionListener(this);
                   // Use actionCommand to store x,y location of button
                   arrayofButtons[row][column].setActionCommand(Integer.toString(row) + " " +
                             Integer.toString(column));
                   panel.add(arrayofButtons[row][column]);
         return panel;
    * Called when user clicks buttons with ActionListeners.
    public void actionPerformed(ActionEvent e) {
         JButton button = (JButton) e.getSource();
         String xORo;
         String rowColumn[] = button.getActionCommand().split(" ");
         int row = Integer.parseInt(rowColumn[0]);
         int column = Integer.parseInt(rowColumn[1]);
         xORo = board.makeMark(row, column);
         if (xORo != null)
              button.setText(xORo);
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event dispatch thread.
    private static void createAndShowGUI() {
         // Create and set up the window.
         JFrame frame = new JFrame("Tic Tac Toe");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         // Add contents to the window.
         frame.add(new TicTacToe());
         // Display the window.
         frame.pack();
         frame.setVisible(true);
    public static void main(String[] args) {
         // Schedule a job for the event-dispatching thread:
         // creating and showing this application's GUI.
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                   createAndShowGUI();
    }

  • Tic Tac Toe Java help!

    Hi, I have been trying to create a simple Tic Tac Toe game using Java. I'm currently having problems as to how to create the board using arrays (sorry I don't understand them very well). All I have so far is this,
    public class ticTacToe {
    private int [] [] theBoard = new int [3] [3];
         // *'N' is no winner
         // 'X' is X won
         // 'O' is O won
         // 'C' is a cat's game
         public static char didSomeoneWin(int [] [] currentBoard)
              int winForX = 8000, winForO = 1, checkIfItsAcatsGame = 1, product;
              char winner = 'N';
              for(int column = 0; column < 3; column++) // Check the columns
                   product = currentBoard [0] [column] * currentBoard [1] [column] * currentBoard [2] [column];
                   if(product == winForX) winner = 'X';
                   if(product == winForO) winner = 'O';
              for(int row = 0; row < 3; row++) // Check the rows
                   product = currentBoard [row] [0] * currentBoard [row] [1] * currentBoard [row] [2];
                   if(product == winForX) winner = 'X';
                   if(product == winForO) winner = 'O';
              product = currentBoard [0] [0] * currentBoard [1] [1] * currentBoard [2] [2]; // Check one diagonal
              if(product == winForX) winner = 'X';
              if(product == winForO) winner = 'O';
              product = currentBoard [0] [2] * currentBoard [1] [1] * currentBoard [2] [0]; // Check the other diagonal
              if(product == winForX) winner = 'X';
              if(product == winForO) winner = 'O';
              if(winner == 'N') // If nobody's won, Check for a cat's game
                   for(int row = 0; row < 3; row++)
                        for(int column = 0; column < 3; column++)
                             checkIfItsAcatsGame *=currentBoard [row] [column];
                   if(checkIfItsAcatsGame != 0) winner = 'C'; // any empty space is a zero. So product is zero if there is space left.
              return winner;
         public void markX(int row, int column)
              myBoard [row] [column] = 20;
         public void markO(int row, int column)
              myBoard [row] [column] = 1;
    That is all so far, could someone help me print out the board? And help me out on the arrays? I don't think they are quite right. Thanks in Advance!
    Message was edited by:
    matthews1.7.2.0

    Hi,
    Do you need a GUI ?
    If yes see http://java.sun.com/docs/books/tutorial/uiswing/index.html
    You can also see this : http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html about printing.
    --Marc (http://jnative.sf.net)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Tic Tac Toe help using array

    Ok i am trying to get a tic tac toe game, which uses array. I need to get 3 buttons and store them then i can check those numbers to see if its a win. Here is my code
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
        public class project4q3 extends JFrame implements ActionListener {
          private JButton buttons[]=new JButton[9];
          private String names[]={"1","2","3",
                                                "4","5","6",
                                                "7","8","9",};
          private int map[][]= {{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8},
             {3,6,9}, {1,5,9}, {3,5,7}};
          private JPanel infoPanel;
          private JLabel player,player2;
          private int row=0,count=0;
          private int whosMove=1;
       // set up GUI and event handling
           public project4q3()
             super( "Tic Tac Toe" );
             infoPanel = new JPanel();
          // two layouts, the upper one is grid style and the
          // lower one is flow style.
             infoPanel.setLayout (new GridLayout(3, 3));
          //Add Button Names
             for(int i=0;i<buttons.length;i++)
                buttons=new JButton(names[i]);
    // direction button objects
    for(int i=0;i<buttons.length;i++)
    buttons[i].addActionListener( this );
    //Grid buttons
    for(int i=0;i<buttons.length;i++)
    infoPanel.add(buttons[i]);
    // grid layout of the main panel, one upper and the other lower
    getContentPane().add(infoPanel);
    setTitle("Tic Tac Toe");
    setSize(400, 400 );
    setVisible( true );
    } // end constructor
    // handle button events because this->actionperformed
    // i.e., (project3q6)->actionPerformed, is added into
    // each button's action
    public void actionPerformed( ActionEvent event ){
    int n1=0,n2=0,n3;
    for(int i=0;i<buttons.length;i++){
    if (event.getSource()==buttons[i])
    n1=Integer.parseInt(names[i]);
    System.out.println(n1);
         System.out.println(n2);
    for(int i = 0; flag == 0 && i< c.length; i++){
              if(n1==c[i][0]&&n2==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if (n1==c[i][0]&&n3==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n1==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n3==c[i][1]&&n1==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n1==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n2==c[i][1]&&n1==c[i][2]){
                   flag = 1;
    // the start of the game
    public static void main( String args[] )
    project4q3 application = new project4q3();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

    I couldn't try this out due to a few syntax errors, so fixed some. Now the buttons seem to work.
       import java.awt.*;
       import java.awt.event.*;
       import javax.swing.*;
        public class project4q3 extends JFrame implements ActionListener {
          private JButton buttons[]=new JButton[9];
          private String names[]={"1","2","3",
                                                "4","5","6",
                                                "7","8","9",};
          private int c[][]= {{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8},
             {3,6,9}, {1,5,9}, {3,5,7}};
          private JPanel infoPanel;
          private JLabel player,player2;
          private int row=0,count=0;
          private int whosMove=1;
    private int flag;
       // set up GUI and event handling
           public project4q3()
             super( "Tic Tac Toe" );
             infoPanel = new JPanel();
          // two layouts, the upper one is grid style and the
          // lower one is flow style.
             infoPanel.setLayout (new GridLayout(3, 3));
          //Add Button Names
             for(int i=0;i<buttons.length;i++)
                buttons=new JButton(names[i]);
    // direction button objects
    for(int i=0;i<buttons.length;i++)
    buttons[i].addActionListener( this );
    //Grid buttons
    for(int i=0;i<buttons.length;i++)
    infoPanel.add(buttons[i]);
    // grid layout of the main panel, one upper and the other lower
    getContentPane().add(infoPanel);
    setTitle("Tic Tac Toe");
    setSize(400, 400 );
    setVisible( true );
    } // end constructor
    // handle button events because this->actionperformed
    // i.e., (project3q6)->actionPerformed, is added into
    // each button's action
    public void actionPerformed( ActionEvent event ){
    int n1=0,n2=0,n3=0;
    for(int i=0;i<buttons.length;i++){
    if (event.getSource()==buttons[i])
    n1=Integer.parseInt(names[i]);
    System.out.println(n1);
         System.out.println(n2);
    for(int i = 0; flag == 0 && i < c.length; i++){
              if(n1==c[i][0]&&n2==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if (n1==c[i][0]&&n3==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n1==c[i][1]&&n3==c[i][2]){
                   flag = 1;
              else if(n2==c[i][0]&&n3==c[i][1]&&n1==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n1==c[i][1]&&n2==c[i][2]){
                   flag = 1;
              else if(n3==c[i][0]&&n2==c[i][1]&&n1==c[i][2]){
                   flag = 1;
    // the start of the game
    public static void main( String[] args)
    project4q3 application = new project4q3();
    application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

  • Help in swing app. tic tac toe

    Trying to make this tic tac toe game. Need a little help. I want the newGameBUT to start the game over, and I would like turnTF to display if a tie occurs. (I tried using *if button.enabled(false) {* but it didn't work. If anyone could help me out, that'd be great. Oh, also, the new game button currently add's 1 to whoever won so far, which is really weird =x. Thanks beforehand.
    import java.awt.*; //import
    import javax.swing.*; //import
    import java.awt.event.*; //import
    import java.awt.Rectangle; //import
    import java.awt.Font; //import
    import javax.swing.BorderFactory; //import
    import javax.swing.border.TitledBorder; //import
    import java.awt.Color; //import
    public class TicTacToeFrame extends JFrame implements ActionListener {
        public TicTacToeFrame() {
            try { //try the following
                jbInit();
            } catch (Exception ex) { // exit on [X]
                ex.printStackTrace(); //exit and print errors
        int xWon = 0; //counting how many times O has won
        int oWon = 0; //counting how many times X has one
        double i = 0; // loop variable to determine turn
        public void actionPerformed(ActionEvent e) {
            String turn = "null"; //current turn
            String notTurn = "null"; //not current turn
            newGameBUT.setEnabled(false); //disable new game button
            if (i % 2 == 0) { // for determining who's turn it is
                turn = "X"; // X's turn when counter is even
                notTurn = "O"; //notTurn used to show who's turn it is in turnTF
            if (i % 2 != 0) { // for determining who's turn it is
                turn = "O"; // O's turn when counter is odd
                notTurn = "X"; //notTurn used to show who's turn it is in turnTF
            turnTF.setText("Currently " + notTurn + "'s turn"); // displays turn
            if (e.getSource() == sqOneBUT) { //disable and print X or O to button
                sqOneBUT.setText(turn); //printing players symbol
                sqOneBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
                sqTwoBUT.setText(turn); //printing players symbol
                sqTwoBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
                sqThreeBUT.setText(turn); //printing players symbol
                sqThreeBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFourBUT) { //disable and print X or O to button
                sqFourBUT.setText(turn); //printing players symbol
                sqFourBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
                sqFiveBUT.setText(turn); //printing players symbol
                sqFiveBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSixBUT) { //disable and print X or O to button
                sqSixBUT.setText(turn); //printing players symbol
                sqSixBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
                sqSevenBUT.setText(turn); //printing players symbol
                sqSevenBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqEightBUT) { //disable and print X or O to button
                sqEightBUT.setText(turn); //printing players symbol
                sqEightBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqNineBUT) { //disable and print X or O to button
                sqNineBUT.setText(turn); //printing players symbol
                sqNineBUT.setEnabled(false); //disabling button
            String sqOne = sqOneBUT.getText(); // Strings to read to find winner
            String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
            String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
            String sqFour = sqFourBUT.getText(); // Strings to read to find winner
            String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
            String sqSix = sqSixBUT.getText(); // Strings to read to find winner
            String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
            String sqEight = sqEightBUT.getText(); // Strings to read to find winner
            String sqNine = sqNineBUT.getText(); // Strings to read to find winner
             OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
             OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
    //horizontal, top, o wins
            if (sqOne == "O") { //checking too see if player O has won
                if (sqFour == "O") {
                    if (sqSeven == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    //vertical, left, o wins
            if (sqOne == "O") { //checking too see if player O has won
                if (sqTwo == "O") {
                    if (sqThree == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top left to bottom right, o wins
            if (sqOne == "O") {
                if (sqFive == "O") { //checking too see if player O has won
                    if (sqNine == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, mid, o wins
            if (sqTwo == "O") { //checking too see if player O has won
                if (sqFive == "O") {
                    if (sqEight == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, bottom, o wins
            if (sqThree == "O") { //checking too see if player O has won
                if (sqSix == "O") {
                    if (sqNine == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top right to bottom left, o wins
            if (sqThree == "O") { //checking too see if player O has won
                if (sqFive == "O") {
                    if (sqSeven == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
             XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
             $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~X WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
             XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    //horizontal, top, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqFour == "X") {
                    if (sqSeven == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    //vertical, left, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqTwo == "X") {
                    if (sqThree == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top left to bottom right, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqNine == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, mid, x wins
            if (sqTwo == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqEight == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, bottom, x wins
            if (sqThree == "X") { //checking too see if player X has won
                if (sqSix == "X") {
                    if (sqNine == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
            // diagonal, top right to bottom left, x wins
            if (sqThree == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqSeven == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
            String wins = turnTF.getText(); //Reading who won to print win winTF
            if (wins.equals("X wins!")) { //if X wins
                xWon++; //adding 1 to X's amount of wins
                String xWonString = Integer.toString(xWon); //converting to String
                xWinsTF.setText(xWonString); //displaying # of wins
                newGameBUT.setEnabled(true); //enable new game button
            if (wins.equals("O wins!")) { //if O wins
                oWon++; //adding 1 to O's amount of wins
                String oWonString = Integer.toString(oWon); //converting to String
                oWinsTF.setText(oWonString); //displaying # of wins
                newGameBUT.setEnabled(true); //enable new game button
            if (e.getSource() == newGameBUT) {
            i++; // turn switch
        /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        private void jbInit() throws Exception {
            this.getContentPane().setLayout(null);
            this.getContentPane().setBackground(Color.darkGray);
            sqTwoBUT.setBounds(new Rectangle(2, 116, 115, 115));
            sqTwoBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqFourBUT.setBounds(new Rectangle(118, 1, 115, 115));
            sqFourBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqFiveBUT.setBounds(new Rectangle(118, 116, 115, 115));
            sqFiveBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqSixBUT.setBounds(new Rectangle(118, 232, 115, 115));
            sqSixBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqOneBUT.setBounds(new Rectangle(2, 1, 115, 115));
            sqOneBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqEightBUT.setBounds(new Rectangle(233, 116, 115, 115));
            sqEightBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqNineBUT.setBounds(new Rectangle(233, 232, 115, 115));
            sqNineBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqSevenBUT.setBounds(new Rectangle(233, 1, 115, 115));
            sqSevenBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqOneBUT.addActionListener(this);
            sqTwoBUT.addActionListener(this);
            sqThreeBUT.addActionListener(this);
            sqFourBUT.addActionListener(this);
            sqFiveBUT.addActionListener(this);
            sqSixBUT.addActionListener(this);
            sqSevenBUT.addActionListener(this);
            sqEightBUT.addActionListener(this);
            sqNineBUT.addActionListener(this);
            newGameBUT.addActionListener(this);
            sqThreeBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            turnTF.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            turnTF.setEditable(false);
            turnTF.setText("X goes first");
            turnTF.setHorizontalAlignment(SwingConstants.CENTER);
            turnTF.setBounds(new Rectangle(2, 346, 346, 35));
            oWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                              Font.BOLD, 18));
            oWinsTF.setEditable(false);
            oWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
            oWinsTF.setBounds(new Rectangle(256, 419, 79, 59));
            xWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                              Font.BOLD, 18));
            xWinsTF.setEditable(false);
            xWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
            xWinsTF.setBounds(new Rectangle(12, 419, 79, 59));
            oWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                               Font.PLAIN, 16));
            oWinsLBL.setForeground(Color.white);
            oWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
            oWinsLBL.setText("O wins:");
            oWinsLBL.setBounds(new Rectangle(256, 399, 78, 21));
            xWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                               Font.PLAIN, 16));
            xWinsLBL.setForeground(Color.white);
            xWinsLBL.setDisplayedMnemonic('0');
            xWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
            xWinsLBL.setText("X wins:");
            xWinsLBL.setBounds(new Rectangle(12, 393, 78, 21));
            newGameBUT.setBounds(new Rectangle(101, 455, 146, 23));
            newGameBUT.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                                 Font.BOLD, 14));
            newGameBUT.setText("New Game");
            this.getContentPane().add(sqFourBUT);
            this.getContentPane().add(sqThreeBUT);
            this.getContentPane().add(sqTwoBUT);
            this.getContentPane().add(sqOneBUT);
            this.getContentPane().add(sqFiveBUT);
            this.getContentPane().add(sqSixBUT);
            this.getContentPane().add(sqNineBUT);
            this.getContentPane().add(sqEightBUT);
            this.getContentPane().add(sqSevenBUT);
            this.getContentPane().add(turnTF);
            this.getContentPane().add(xWinsLBL);
            this.getContentPane().add(xWinsTF);
            this.getContentPane().add(oWinsLBL);
            this.getContentPane().add(oWinsTF);
            this.getContentPane().add(newGameBUT);
            sqThreeBUT.setBounds(new Rectangle(2, 232, 115, 115));
        JButton sqTwoBUT = new JButton();
        JButton sqThreeBUT = new JButton();
        JButton sqFourBUT = new JButton();
        JButton sqFiveBUT = new JButton();
        JButton sqSixBUT = new JButton();
        JButton sqOneBUT = new JButton();
        JButton sqEightBUT = new JButton();
        JButton sqNineBUT = new JButton();
        JButton sqSevenBUT = new JButton();
        JTextField turnTF = new JTextField();
        JTextField oWinsTF = new JTextField();
        JTextField xWinsTF = new JTextField();
        JLabel oWinsLBL = new JLabel();
        JLabel xWinsLBL = new JLabel();
        JButton newGameBUT = new JButton();
    }

    This code should be the poster-child for every time we tell someone that repeated code can usually be replaced with collections or method calls.
            if (e.getSource() == sqOneBUT) { //disable and print X or O to button
                sqOneBUT.setText(turn); //printing players symbol
                sqOneBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
                sqTwoBUT.setText(turn); //printing players symbol
                sqTwoBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
                sqThreeBUT.setText(turn); //printing players symbol
                sqThreeBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFourBUT) { //disable and print X or O to button
                sqFourBUT.setText(turn); //printing players symbol
                sqFourBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
                sqFiveBUT.setText(turn); //printing players symbol
                sqFiveBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSixBUT) { //disable and print X or O to button
                sqSixBUT.setText(turn); //printing players symbol
                sqSixBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
                sqSevenBUT.setText(turn); //printing players symbol
                sqSevenBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqEightBUT) { //disable and print X or O to button
                sqEightBUT.setText(turn); //printing players symbol
                sqEightBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqNineBUT) { //disable and print X or O to button
                sqNineBUT.setText(turn); //printing players symbol
                sqNineBUT.setEnabled(false); //disabling button
            String sqOne = sqOneBUT.getText(); // Strings to read to find winner
            String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
            String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
            String sqFour = sqFourBUT.getText(); // Strings to read to find winner
            String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
            String sqSix = sqSixBUT.getText(); // Strings to read to find winner
            String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
            String sqEight = sqEightBUT.getText(); // Strings to read to find winner
            String sqNine = sqNineBUT.getText(); // Strings to read to find winner

  • Need some help with Tic Tac Toe game

    hey. hope u guys can help me out...
    having a problem with my tic tac toe program...
    i have 2 problems.
    1) got the "X" and "O" to appear using a flag(teacher didn't explain)
    using code like this
    if (jb == button[0]){
    if (flag==0)
    button[0].setText("X");
    else
    button[0].setText("O");
    //toggle
    flag = (flag==0)?1:0;
    my problem is how do i get it to stop.(For example button[1] is selected as "X"..how do i stop it from albe to switch to "O")
    2) found this code in javascript online and i want to do what it does in java code
    if(button[0] == " X " && button[1] == " X " && button[2] == " X ")
    alert("You Win!");
    reset();
    how would i do that?
    thanks for the help.

    ok here's my code:
    //TTT.java
    import javax.swing.*;
    import java.awt.*;
    import java .awt.event.*;
    public class TTT extends JFrame
                        implements WindowListener, ActionListener
    private JFrame frFirst;
    private Container cnFirst,cnSecond;
    private     JButton button[]=new JButton[9];
    private JButton btnNewGame,btnExit;
    private FlowLayout southLayout;
    private JPanel southPanel;
    private int flag;
    public TTT()
                   frFirst=new JFrame ("Michael's Tic Tac Toe Game!");
                   cnFirst=frFirst.getContentPane();
                   cnFirst.setLayout (new GridLayout (4,4));
                   cnFirst.setBackground(Color.green);
              for(int i=0;i<button.length;i++)
                        button[i] = new JButton();
                        cnFirst.add(button);
                        flag=0;
              southPanel = new JPanel ();
              btnNewGame = new JButton ("New Game");
              southPanel.add (btnNewGame);
              btnExit = new JButton ("EXIT");
              southPanel.add (btnExit);
              frFirst.add (southPanel,BorderLayout.SOUTH);
              frFirst.setLocation(200, 200);
              frFirst.setSize(400,400);
              frFirst.setResizable(false);
              frFirst.setVisible(true);
              this.frFirst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   // listeners
                   frFirst.addWindowListener(this);
                   button[0].addActionListener(this);
                   button[1].addActionListener(this);
                   button[2].addActionListener(this);
                   button[3].addActionListener(this);
                   button[4].addActionListener(this);
                   button[5].addActionListener(this);
                   button[6].addActionListener(this);
                   button[7].addActionListener(this);
                   button[8].addActionListener(this);
                   btnNewGame.addActionListener (this);
                   btnExit.addActionListener (this);
         //define methods of WindowListener
    public void windowOpened(WindowEvent we)
         public void windowClosing(WindowEvent we)
         System.exit(0);
         public void windowClosed(WindowEvent we)
         public void windowIconified(WindowEvent we)
         public void windowDeiconified(WindowEvent we)
         public void windowActivated(WindowEvent we)
         public void windowDeactivated(WindowEvent we)
    public void actionPerformed(ActionEvent ae)
    //making the X and O to appear on JButtons
         Object obj = ae.getSource();
              if (obj instanceof JButton){
                   JButton jb = (JButton)obj;
                   if (jb == button[0])
                        if (flag==0)
                        button[0].setText("X");
                   else
                        button[0].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[1])
                        if (flag==0)
                        button[1].setText("X");
                   else
                        button[1].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[2])
                        if (flag==0)
                        button[2].setText("X");
                   else
                        button[2].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[3])
                        if (flag==0)
                        button[3].setText("X");
                   else
                        button[3].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[4])
                        if (flag==0)
                        button[4].setText("X");
                   else
                        button[4].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[5])
                        if (flag==0)
                        button[5].setText("X");
                   else
                        button[5].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[6])
                        if (flag==0)
                        button[6].setText("X");
                   else
                        button[6].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[7])
                        if (flag==0)
                        button[7].setText("X");
                   else
                        button[7].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
                   if(jb==button[8])
                        if (flag==0)
                        button[8].setText("X");
                   else
                        button[8].setText("O");
                        //toggle
                        flag = (flag==0)?1:0;
    //New Game To Reset
              if (ae.getSource () == btnNewGame)
    /*     String text = JOptionPane.showInputDialog(null,"Do You Want To Start A New Game?","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
    String YES;
    if (text == YES)
         JOptionPane.showMessageDialog(null,"Do You","Michael's Tic Tac Toe Game!",JOptionPane.WARNING_MESSAGE);
         else{
    add code to reset game
         //Exit Button to Exit
         if (ae.getSource () == btnExit)
              JOptionPane.showMessageDialog(null,"Thanks For Playing!","Michael's Tic Tac Toe Game!",JOptionPane.INFORMATION_MESSAGE);
              this.setVisible(false);
         System.exit(0);
              }     //end of if instanceof
    public static void main(String[]args)
         //instantiate GUI
         new TTT();

  • Making a tic tac toe grid

    hi, I've created my code and for the tic tac toe grid but I dont know how to make it look like a grid (i.e
    1 2 3
    4 5 6
    7 8 9)
    it has came out as "123X56789" "X" meaning a number has taken up a cross.
    can anyone help??
    heres the code of the grid........
    // GAMEINTERFACE
    public class GameInterface extends MyPrint
         private String theGrid;
         final static char NOUGHT='O', CROSS='X';
         public GameInterface()
         theGrid = "?123456789";
         public void pictureBoard(String theGrid)
    for(int i = 1; i<theGrid.length(); i++)
              int hit = i%3;
              if(hit!=0)
                   myPrint(Character.toString((theGrid.charAt(i))));
              else
                   myPrint(Character.toString((theGrid.charAt(i))));
         public void play(char cell, boolean playTurn)
              char noughtCross = ' ';
              if(playTurn = true)
                   noughtCross = CROSS;
              else if(playTurn = false)
                   noughtCross = NOUGHT;
              if('1'<=cell || cell<='9')
                   theGrid=theGrid.substring(0,theGrid.indexOf(cell)) + Character.toString(CROSS) + theGrid.substring(theGrid.indexOf(cell)+1);
              else if('1'<=cell || cell<='9')
                   theGrid=theGrid.substring(0,theGrid.indexOf(cell)) + Character.toString(NOUGHT) + theGrid.substring(theGrid.indexOf(cell)+1);
         public String display()
              return theGrid;
    Plus how do i create a 'O' in the output as 'X' appears for the 2 players playing.
    this will be very appreciated.
    many thanks
    Dave

    just tried that warnerja, it doesnt work either.
    it has to be linked to this other class(program below)
    //GAME
    public class Game extends MyPrint
         GameInterface gameInterface;
         String s = "?123456789";
         Player player1;
         Player player2;
         public Game() // Constructor
         public void makeMove()
              gameInterface = new GameInterface ();
              player1 = new Player ();
              player2 = new Player ();
              myPrintln("Enter name of player");
              String FP = c.input.readString();
              myPrintln(FP, SYSTEM);
              myPrintln("Enter name of other player");
              String SP = c.input.readString();
              myPrintln(SP, SYSTEM);
              gameInterface.pictureBoard(s);
              myPrintln("");
              //boolean whoWon=false;
              int loop = 0;
              while(loop<=6)
                   player1.setName(FP);
                   myPrintln(player1.getName() + " (X) to play");
                   myPrintln("Enter move by selecting number from grid");
                   myPrintln("or 0 to draw");
                   char name1 = c.input.readChar();
                   name1 = c.input.readChar();
                   boolean playTurn = true;
                   gameInterface.play(name1, true);
                   gameInterface.pictureBoard(gameInterface.display());
                   myPrintln("");
                   //if(checkWin(gameInt.display()))
                   //     whoWon=true;
                   //     break;
                   player2.setName(SP);
                   myPrintln(player2.getName() + " (O) to play");
    myPrintln("Enter move by selecting number from grid");
                   myPrintln("or 0 to draw");
                   char name2 = c.input.readChar();
                   name2 = c.input.readChar();
                   playTurn = false;
                   gameInterface.play(name2, false);
                   gameInterface.pictureBoard(gameInterface.display());
                   myPrintln("");
                   //if(checkWin(gameInt.display()))
                   //     whoWon=true;
                   //     break;
                   loop++;
    }

  • Computer AI for Tic-Tac-Toe

    Hi, I'm pretty new to java. I've taken some classes but I don't know much. I am trying to create a Tic-Tac-Toe application and I want to create a computer that will play all the correct moves and never lose. I'm not finished with the moves that the computer makes. I've tagged where I'm having the problems. Here it is:package mytictactoe;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    * Models a TicTacToe game.
    * @author Charles Lockner
    public class SupermanTicTacToe
       // Instance Variables
       private JFrame theFrame = new JFrame("Superman Tic-Tac-Toe");
       private JMenuBar theMenuBar = new JMenuBar();
       private JMenu fileMenu = new JMenu("File");
       private JMenuItem quit = new JMenuItem("Quit");
       private JMenu optionsMenu = new JMenu("Options");
       private JMenuItem reset = new JMenuItem("Reset Game");
       private JMenuItem vsComp = new JMenuItem("Human vs Superman");
       private JMenuItem vsHuman = new JMenuItem("Human vs Human");
       private JButton buttons[] = new JButton[9];
       private int[][] winCombinations = new int[][]
             { 0, 1, 2 },
             { 3, 4, 5 },
             { 6, 7, 8 }, // Horizontal wins
             { 0, 3, 6 },
             { 1, 4, 7 },
             { 2, 5, 8 }, // Vertical wins
             { 0, 4, 8 },
             { 2, 4, 6 } // Diagonal wins
       private String letter = "";
       private int count = 0;
       private boolean win = false;
       private boolean compPlayer = false;
       private boolean playerIsFirst = true;
       private Random generator = new Random();
       public SupermanTicTacToe()
          // Create window
          theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          theFrame.setSize(300,340);
          theFrame.setLayout(new GridLayout(3,3));
          theFrame.setLocationRelativeTo(null);
          theFrame.setResizable(false);
          // Add menu to window
          theMenuBar.add(fileMenu);
          fileMenu.add(quit);
          theMenuBar.add(optionsMenu);
          optionsMenu.add(reset);
          optionsMenu.addSeparator();
          optionsMenu.add(vsComp);
          optionsMenu.add(vsHuman);
          theFrame.setJMenuBar(theMenuBar);
          // Add buttons to panel
          for(int i = 0; i <= 8; i++)
             buttons[i] = new JButton();
             theFrame.add(buttons);
    // Make Window Visible
    theFrame.setVisible(true);
    // Actions
    quit.addActionListener(new QuitMenuListener());
    reset.addActionListener(new ResetMenuListener());
    vsComp.addActionListener(new VsCompMenuListener());
    vsHuman.addActionListener(new VsHumanMenuListener());
    for(int i = 0; i <= 8; i++)
    buttons[i].addActionListener(new ButtonListener());
    private class ButtonListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    count++;
    System.out.println("Button click done.");
    // Calculate whose turn it is
    if (count % 2 == 0)
    letter = "O";
    else
    letter = "X";
    JButton pressedButton = (JButton) e.getSource();
    pressedButton.setText(letter);
    pressedButton.setEnabled(false);
    // Determine who won
    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;
    // Show a dialog when game is over
    if (win == true)
    for (int i = 0; i <= 8; i++)
    buttons[i].setEnabled(false);
    JOptionPane.showMessageDialog(null, letter + " is a beast.");
    } else if (count == 9 && win == false)
    JOptionPane.showMessageDialog(null, "No one is beastly enough to win this game.");
    // Computer's actions PROBLEMS!!!=====================================
    if (compPlayer)
    if (playerIsFirst)
    if (letter == "O")
    if (buttons[4].getText().equals(""))
    buttons[4].doClick();
    else if (buttons[0].getText().equals(""))
    buttons[0].doClick();
    else if (buttons[2].getText().equals(""))
    buttons[2].doClick();
    else if (buttons[6].getText().equals(""))
    buttons[6].doClick();
    else if (buttons[8].getText().equals(""))
    buttons[8].doClick();
    } else
    if (letter == "X")
    if (buttons[0].getText().equals(""))
    buttons[0].doClick();
    else if (buttons[2].getText().equals(""))
    buttons[2].doClick();
    else if (buttons[6].getText().equals(""))
    buttons[6].doClick();
    else if (buttons[8].getText().equals(""))
    buttons[8].doClick();
    } //==================================================================
    private class QuitMenuListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    System.exit(0);
    private class ResetMenuListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    for (int i = 0; i <= 8; i++)
    playerIsFirst = generator.nextBoolean();
    buttons[i].setEnabled(true);
    buttons[i].setText("");
    count = 0;
    win = false;
    if(playerIsFirst = false)
    buttons[4].doClick();
    private class VsCompMenuListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    for (int i = 0; i <= 8; i++)
    buttons[i].setEnabled(true);
    buttons[i].setText("");
    count = 0;
    win = false;
    compPlayer = true;
    playerIsFirst = generator.nextBoolean();
    System.out.println(playerIsFirst);
    if(playerIsFirst = false)
    buttons[4].doClick();
    private class VsHumanMenuListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    for (int i = 0; i <= 8; i++)
    playerIsFirst = generator.nextBoolean();
    buttons[i].setEnabled(true);
    buttons[i].setText("");
    count = 0;
    win = false;
    compPlayer = false;
    public static void main(String[] args)
    new SupermanTicTacToe();

    Here is updated code, that I believe will not be beatable by human input. Let me know if you find any bugs.
    -Squeaker2
             // Computer's actions
             if (compPlayer)
                 if (letter.contentEquals("O")){}
                 else if(letter.contentEquals("X"))
                   {//Code Computer AI Logic
                      boolean flagger = false;
                      flagger = computerLogic();
                      if (flagger == false){
                          if (buttons[4].getText().contentEquals(""))
                             buttons[4].doClick();
                          //Check for inside
                          else if (buttons[1].getText().contentEquals("X")
                                  && buttons[5].getText().contentEquals("X")
                                  && buttons[2].getText().contentEquals(""))
                                buttons[2].doClick();
                          else if (buttons[7].getText().contentEquals("X")
                                  && buttons[5].getText().contentEquals("X")
                                  && buttons[8].getText().contentEquals(""))
                                buttons[8].doClick();
                          else if (buttons[3].getText().contentEquals("X")
                                  && buttons[7].getText().contentEquals("X")
                                  && buttons[6].getText().contentEquals(""))
                                buttons[6].doClick();
                          else if (buttons[1].getText().contentEquals("X")
                                  && buttons[3].getText().contentEquals("X")
                                  && buttons[0].getText().contentEquals(""))
                                buttons[0].doClick();
                          else if (buttons[4].getText().contentEquals("X")
                                  && buttons[0].getText().contentEquals(""))
                                buttons[0].doClick();
                          else if (buttons[1].getText().contentEquals(""))
                             buttons[1].doClick();
                          else if (buttons[3].getText().contentEquals(""))
                             buttons[3].doClick();
                          else if (buttons[5].getText().contentEquals(""))
                             buttons[5].doClick();
                          else if (buttons[7].getText().contentEquals(""))
                             buttons[7].doClick();
                          else if (buttons[0].getText().contentEquals(""))
                             buttons[0].doClick();
                          else if (buttons[2].getText().contentEquals(""))
                             buttons[2].doClick();
                          else if (buttons[6].getText().contentEquals(""))
                             buttons[6].doClick();
                          else if (buttons[8].getText().contentEquals(""))
                             buttons[8].doClick();
       public boolean computerLogic(){
           boolean flagger = false;
           boolean turnUsed = false;
            for (int i = 0; i <= 7; i++)
             { //Check for WIN loop
                if (turnUsed == false){
                    if (buttons[winCombinations[0]].getText().equals(buttons[winCombinations[i][1]].getText()) && buttons[winCombinations[i][0]].getText().contentEquals("O") && buttons[winCombinations[i][2]].getText().contentEquals(""))
    buttons[winCombinations[i][2]].doClick();
    flagger = true;
    turnUsed = true;
    else if (buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) && buttons[winCombinations[i][1]].getText().contentEquals("O") && buttons[winCombinations[i][0]].getText().contentEquals(""))
    buttons[winCombinations[i][0]].doClick();
    flagger = true;
    turnUsed = true;
    else if (buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][2]].getText()) && buttons[winCombinations[i][2]].getText().contentEquals("O") && buttons[winCombinations[i][1]].getText().contentEquals(""))
    buttons[winCombinations[i][1]].doClick();
    flagger = true;
    turnUsed = true;
    for (int i = 0; i <= 7; i++)
    { //Check for Block Loop
    if (turnUsed == false){
    if (buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) && buttons[winCombinations[i][0]].getText().contentEquals("X") && buttons[winCombinations[i][2]].getText().contentEquals(""))
    buttons[winCombinations[i][2]].doClick();
    flagger = true;
    turnUsed = true;
    else if (buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) && buttons[winCombinations[i][1]].getText().contentEquals("X") && buttons[winCombinations[i][0]].getText().contentEquals(""))
    buttons[winCombinations[i][0]].doClick();
    flagger = true;
    turnUsed = true;
    else if (buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][2]].getText()) && buttons[winCombinations[i][2]].getText().contentEquals("X") && buttons[winCombinations[i][1]].getText().contentEquals(""))
    buttons[winCombinations[i][1]].doClick();
    flagger = true;
    turnUsed = true;
    return flagger;

  • Tic Tac Toe with AI

    Well I'm getting ready for my second semester of Java programing and I figured I would try and get back in the swing (no pun intended) of things by creating a simple tic tac toe game. I was able to make a two player game with in a matter of hours so I figured I would try and make a one player game with AI and thats where im having some issues. Here is my code for two person tic tac toe
    package mytictactoe;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TicTacToeV2 implements ActionListener {
         /*Instance Variables*/
         private int[][] winCombinations = new int[][] {
                   {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, //horizontal wins
                   {1, 4, 7}, {2, 5, 8}, {3, 6, 9}, //virticle wins
                   {1, 5, 9}, {3, 5, 7}                //diagonal wins
         private JFrame window = new JFrame("Tic-Tac-Toe");
         private JButton buttons[] = new JButton[10];
         private int count = 0;
         private String letter = "";
         private boolean win = false;
         public TicTacToeV2(){
         /*Create Window*/
         window.setSize(300,300);
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         window.setLayout(new GridLayout(3,3));
         /*Add Buttons To The Window*/
         for(int i=1; i<=9; i++){
              buttons[i] = new JButton();
              window.add(buttons);
              buttons[i].addActionListener(this);
         /*Make The Window Visible*/
         window.setVisible(true);
         public void actionPerformed(ActionEvent a) {
              count++;
              /*Calculate whose turn it is*/
              if(count % 2 == 0){
                   letter = "O";
              } else {
                   letter = "X";
              /*Write the letter to the button and deactivate it*/
              for(int i=1; i<=9; i++){
                   if(a.getSource() == buttons[i]){
                        buttons[i].setText(letter);
                        buttons[i].setEnabled(false);
              /*Determine who won*/
              for(int i=0; i<=7; i++){
                   if( buttons[winCombinations[i][0]].getText() == buttons[winCombinations[i][1]].getText() &&
                        buttons[winCombinations[i][1]].getText() == buttons[winCombinations[i][2]].getText() &&
                        buttons[winCombinations[i][0]].getText() != ""){
                        win = true;
              /*Show a dialog when game is over*/
              if(win == true){
                   JOptionPane.showMessageDialog(null, letter + " wins the game!");
                   System.exit(0);
              } else if(count == 9 && win == false){
                   JOptionPane.showMessageDialog(null, "The game was tie!");
                   System.exit(0);
         public static void main(String[] args){
              TicTacToeV2 starter = new TicTacToeV2();
    Now for my program with AI I'm essentially using the same code and just for clarity I removed all the code that determines who won (as it isnt needed to get the AI to work) This is what I have so far
    package mytictactoe;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    public class TicTacToeV3 implements ActionListener {
         /*Instance Variables*/
         private JFrame window = new JFrame("Tic-Tac-Toe");
         private JButton buttons[] = new JButton[10];
         private int count = 0;
         public TicTacToeV3(){
         /*Create Window*/
         window.setSize(300,300);
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         window.setLayout(new GridLayout(3,3));
         /*Add Buttons To The Window*/
         for(int i = 1; i<=9; i++){
              buttons[i] = new JButton();
              window.add(buttons);
              buttons[i].addActionListener(this);
         /*Make The Window Visible*/
         window.setVisible(true);
         public void actionPerformed(ActionEvent a) {
              count++;
              /*Write the letter to the button and deactivate it*/
              for(int i = 1; i<= 9; i++){
                   if(a.getSource() == buttons[i]){
                        buttons[i].setText("X");
                        buttons[i].setEnabled(false);
              AI();
         public void AI(){
              Random x = new Random();
              int y = 1 + x.nextInt(9);
              if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                   AI();
              } else {
                   buttons[y].setText("O");
                   buttons[y].setEnabled(false);
         public static void main(String[] args){
              new TicTacToeV3();
    It kind of works because each time i choose a box the "computer" also chooses one, but since it is so random the chances the computer wins is very limited. I then tried to do something like this in the AI() method and it seems to be on the right track but once one of the if's are satisfied the all the AI logic stops
         public void AI(){
              //horizontal AI defencive code
              if(buttons[1].getText().equals(buttons[2].getText()) && buttons[1].getText() != ""){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);
              } else if(buttons[2].getText().equals(buttons[3].getText()) && buttons[2].getText() != ""){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);
              } else if(buttons[4].getText().equals(buttons[5].getText()) && buttons[4].getText() != ""){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);
              } else if(buttons[5].getText().equals(buttons[6].getText()) && buttons[5].getText() != ""){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);
              } else if(buttons[7].getText().equals(buttons[8].getText()) && buttons[7].getText() != ""){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);
              } else if(buttons[8].getText().equals(buttons[9].getText()) && buttons[8].getText() != ""){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);
              } else {
                   Random x = new Random();
                   int y = 1 + x.nextInt(9);
                   if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                        AI();
                   } else {
                        buttons[y].setText("O");
                        buttons[y].setEnabled(false);
         }And basically what that does is it checks if I have two X's in a row horizontally, If I do it will place an O in the box preventing me from getting three in a row (only in horizontal rows). Of course I would iterate this over and over for all possible combinations of offensive moves and defensive moves and probably do it using a for loop but this is just some scratch code I threw together to show you my thoughts. And again my problem is once one of the conditions are satisfied it never checks the conditions again and I'm not sure why that is...
    So I'm looking for some ideas and/or some pseudo code to help me out a little.
    Thanks

    Well I did this and its a step closer to working but there is another bug and all this logic is hurting my head. Again lets say my grid is numbered like this
    1 | 2 | 3
    4 | 5 | 6
    7 | 8 | 9
    If I go 1, the computer will randomly pick a square thats not set. Lets say the computer picks 4. Now I pick 5 and the computer picks 9 because I would earn 3 in a row diagonally. Then I pick 2 and I can now win three in a row 2-5-8 or 1-2-3. The computer picks 3 because that logic is earlier in the code. BUT when I press 8 to to take the win, but the computer cheats and labels my button thats supposed to be an X as an O, so it should look like this:
    X | X | O
    O | X | 6
    7 | X | O
    but it does this
    X | X | O
    O | X | 6
    7 | O | O
    Here is the AI logic part (its mostly repetitive)
         public void AI(){
              /*Defencive Moves*/
              //horizontal defencive possabilities
              if((buttons[1].getText() == "X")&&
                        (buttons[2].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);
              } else if((buttons[2].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[4].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              }  else if((buttons[8].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              }  else if((buttons[1].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              }  else if((buttons[4].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              }  else if((buttons[7].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              //horizontal virticle possabilities
                else if((buttons[1].getText() == "X")&&
                             (buttons[4].getText() == "X")&&
                             (buttons[7].getText() != "O")){
                        buttons[7].setText("O");
                        buttons[7].setEnabled(false);               
              }  else if((buttons[7].getText() == "X")&&
                        (buttons[4].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              }  else if((buttons[1].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              }  else if((buttons[2].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              }  else if((buttons[5].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              }  else if((buttons[2].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              }  else if((buttons[6].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);
              //diagonal
              else if((buttons[1].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              }  else if((buttons[5].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              }  else if((buttons[1].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              }  else if((buttons[5].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              }  else if((buttons[3].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              //random move
              else {
                   RandomMove();
         public void RandomMove(){
              Random x = new Random();
              int y = 1 + x.nextInt(9);
              if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                   AI();
                   went = true;
              } else {
                   buttons[y].setText("O");
                   buttons[y].setEnabled(false);
                   went = true;
         }Here is the entire code if you want to try it and compile it to see what im talking about in real time:
    package mytictactoe;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    public class TicTacToeV4 implements ActionListener {
         /*Instance Variables*/
         private JFrame window = new JFrame("Tic-Tac-Toe");
         private JButton buttons[] = new JButton[10];
         private int count = 0;
         private boolean went = false;
         public TicTacToeV4(){
         /*Create Window*/
         window.setSize(300,300);
         window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         window.setLayout(new GridLayout(3,3));
         /*Add Buttons To The Window*/
         for(int i = 1; i<=9; i++){
              buttons[i] = new JButton();
              window.add(buttons);
              buttons[i].addActionListener(this);
         /*Make The Window Visible*/
         window.setVisible(true);
         public void actionPerformed(ActionEvent a) {
              count++;
              /*Write the letter to the button and deactivate it*/
              for(int i = 1; i<= 9; i++){
                   if(a.getSource() == buttons[i]){
                        buttons[i].setText("X");
                        buttons[i].setEnabled(false);
              AI();
         public void AI(){
              /*Defencive Moves*/
              //horizontal defencive possabilities
              if((buttons[1].getText() == "X")&&
                        (buttons[2].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);
              } else if((buttons[2].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[4].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              } else if((buttons[8].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              } else if((buttons[1].getText() == "X")&&
                        (buttons[3].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              } else if((buttons[4].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              //horizontal virticle possabilities
              else if((buttons[1].getText() == "X")&&
                             (buttons[4].getText() == "X")&&
                             (buttons[7].getText() != "O")){
                        buttons[7].setText("O");
                        buttons[7].setEnabled(false);               
              } else if((buttons[7].getText() == "X")&&
                        (buttons[4].getText() == "X")&&
                        (buttons[1].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[1].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[4].getText() != "O")){
                   buttons[4].setText("O");
                   buttons[4].setEnabled(false);               
              } else if((buttons[2].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[8].getText() != "O")){
                   buttons[8].setText("O");
                   buttons[8].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[2].getText() != "O")){
                   buttons[2].setText("O");
                   buttons[2].setEnabled(false);               
              } else if((buttons[2].getText() == "X")&&
                        (buttons[8].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[6].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              } else if((buttons[6].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[6].getText() != "O")){
                   buttons[6].setText("O");
                   buttons[6].setEnabled(false);
              //diagonal
              else if((buttons[1].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[9].setText("O");
                   buttons[9].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[9].getText() != "O")){
                   buttons[1].setText("O");
                   buttons[1].setEnabled(false);               
              } else if((buttons[1].getText() == "X")&&
                        (buttons[9].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[5].getText() == "X")&&
                        (buttons[7].getText() != "O")){
                   buttons[7].setText("O");
                   buttons[7].setEnabled(false);               
              } else if((buttons[5].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[3].getText() != "O")){
                   buttons[3].setText("O");
                   buttons[3].setEnabled(false);               
              } else if((buttons[3].getText() == "X")&&
                        (buttons[7].getText() == "X")&&
                        (buttons[5].getText() != "O")){
                   buttons[5].setText("O");
                   buttons[5].setEnabled(false);               
              //random move
              else {
                   RandomMove();
         public void RandomMove(){
              Random x = new Random();
              int y = 1 + x.nextInt(9);
              if(buttons[y].getText() == "X" || buttons[y].getText() == "O" ){
                   AI();
                   went = true;
              } else {
                   buttons[y].setText("O");
                   buttons[y].setEnabled(false);
                   went = true;
         public static void main(String[] args){
              new TicTacToeV4();
    What am I doing wrong?

  • Tic-Tac-Toe [ What would you do different? ]

    I was bored so I made a simple 2-player tic-tac-toe game. I was just wondering if there was any room for improvement [other than the lack of comments]
    package tictactoe;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    public class TicTacToe {
         private char[] board = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9'};
         private int count = 0;
         private int location;
         private int[][] winCombinations = new int[][] {
                   {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
                   {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //virticle wins
                   {0, 4, 8}, {2, 4, 6}                //diagonal wins
         private InputStreamReader isr = new InputStreamReader(System.in);
         private BufferedReader br = new BufferedReader(isr);
         private boolean win = false;
         public TicTacToe(){
              while(checkWin() != true && count < 9){
                   displayBoard();
                   getInput();
                   setLocation();
                   count++;
              endGame();     
         public void displayBoard(){
              System.out.println( board[0] + " | " + board[1] + " | " + board[2]);
              System.out.println("---------");
              System.out.println( board[3] + " | " + board[4] + " | " + board[5]);
              System.out.println("---------");
              System.out.println( board[6] + " | " + board[7] + " | " + board[8]);
              System.out.println("\n");
         public void getInput(){
              System.out.print("Enter the location on the board: ");
              try {
                   //Convert the string to an integer
                   location = Integer.parseInt(br.readLine());
              } catch(Exception Error) {
                   System.out.print("You have entered an invalid number. You must enter a number between 1 and 9 inclusive. Try again.\n\n");
                   getInput();
              if(location < 1 || location > 9){
                   System.out.println("You must enter a number between 1 and 9 inclusive. Try again.\n\n");
                   getInput();
         public void setLocation(){
              if(count % 2 == 0)
                   board[location-1] = 'X';
              else
                   board[location-1] = 'O';
         public boolean checkWin(){
              for(int i=0; i<=7; i++){
                   if( board[winCombinations[0]] == board[winCombinations[i][1]] &&
                        board[winCombinations[i][1]] == board[winCombinations[i][2]]){
                        win = true;
              return win;
         public void endGame(){
              if(checkWin() != true && count == 9){
                   displayBoard();
                   System.out.println("The game is tie!");
              } else {
                   displayBoard();
                   System.out.println("\n\n" + board[location-1] + " WINS!");
              System.exit(0);
         public static void main(String args[]){
              new TicTacToe();
    Thanks.

    1. disassociate any program logic from UI so that it
    can easily be ported to a GUI such as swing>
    As for 1, are you talking about the getInput method?
    Thats the only method that associates logic with UI
    as far as I'm concerned and when it is ported into a
    GUI, the user wont have the ability to select a
    square out of range so that logic wont even exist. Is
    there any other?What I mean is can you take the core logic portion of your code and easily plug it directly to your GUI code or non-GUI code or even changed different GUI code. This can occur if the logic portion is so well encapsulated that it doesn't depend at all on the user interface. another way to put it is the core functionality of the program should not reside in the GUI class (or classes).
    Admittedly w/ 2-D tictactoe, this may not be quite so relevant.
    addendum: check out Model-view-controller on wikipedia.
    Message was edited by:
    petes1234

  • Tic Tac Toe Coding Challenge

    Here is the new coding challenge!!!  You need to create a vi that will play the game of tic tac toe.  It will be played on a 4x4 grid, and the objective is to LOSE the game, not win.  The complete rules are found on the LabVIEW Zone.
    The attached template has the required inputs and outputs for testing.  If you don't use this template, I will not be able to test your submission.
    I will answer any questions about the challenge on this forum.  Please post your questions here and don't email them to me.
    Once there are a few submissions, I will start posting the current standings and update them frequently.
    Can you be the biggest loser?
    Bruce
    Bruce Ammons
    Ammons Engineering
    Attachments:
    Tic Tac Toe Template1.zip ‏46 KB

    TiTou a écrit:...For french speaker who ignore what tic tac toe is, it's "le morpion" in french...
    ....  OK so we have to be the best looser ?  ahem... just a reminder : a "morpion" in french is a crab loose. Now, where is this thread where I was fired down for trying to entertain the BreakPoint board with a classic (albeit silly...) french joke ? Message Edité par chilly charly le 04-27-2006 12:53 PM
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        

  • Help with printing a tic tac toe board (using a loop to print)

    hey im making the smiple game tic tac toe and im tryin to print out the board after each turn. I have a 2d array called char which is a 3 by 3 array and i dont know how i would make a for loop to print out the x's and o's in their right spot and still have the board look like a normal tic tac toe board. When the board is printing the x's and o's are already in the 2d char array board.So basically what i want to happen is after player 1's turn is up wherever he put the x replace the number on the board with an x and keep the rest the same and whenever player 2's turn is up wherever he put the o replace the number on the board with an o and keep the rest the same. Any help would be awesome thanks alot.
    Here is the code to the program (i know i use if statements to much its a bad habit of mine)
    import java.util.*;
    public class Tictactoe
        private char board [] [] = new board [3] [3];
        private int X;
        private int O;
        private Scanner p1choice;
        private Scanner p2choice;
        Scanner input = new Scanner(System.in);
        public Tictactoe()
            p1choice = new Scanner(System.in);
            p2choice = new Scanner(System.in);
            play();
        public void play()
            printoriginalboard();
        public void printoriginalboard()
            System.out.println("    |    |    ");  
            System.out.println("  3 |  2 |  1 ");
            System.out.println("____|____|____");
            System.out.println("    |    |    ");
            System.out.println("  6 |  5 |  4 ");
            System.out.println("    |    |    ");
            System.out.println("____|____|____");
            System.out.println("    |    |    ");
            System.out.println("  9 |  8 |  7 ");
            System.out.println("    |    |    ");
            System.out.println("This is the classic game of tictactoe simply pick a number 1 through 9 to place an x or an o in that area.");
            player1turn();
        public void player1turn()
            System.out.println("Player 1 pick an area to place an X");
            int p1choice= p1choice.nextInt();
            if(p1choice == 1 && p2choice == 1 || p1choice == 1){
                System.out.println("This spot has already been taken");
                else
                board[0][2] = 'x';
            pintboard();
            if(p1choice == 2 && p2choice == 2 || p1choice == 2){
            System.out.println("This spot has already been taken");
            else
                board[1][2] = 'x';
            pintboard();
            if(p1choice == 3 && p2choice == 3 || p1choice == 3){
            System.out.println("This spot has already been taken");
            else
                board[2][2] = 'x';
            pintboard();
            if(p1choice == 4 && p2choice == 4 || p1choice == 4){
            System.out.println("This spot has already been taken");
                board[0][1] = 'x';
            pintboard();
            if(p1choice == 5 && p2choice == 5 || p1choice == 5){
            System.out.println("This spot has already been taken");
            else
                board[1][1] = 'x';
            pintboard();
            if(p1choice == 6 && p2choice == 6 || p1choice == 6){
            System.out.println("This spot has already been taken");
            else
                board[2][1] = 'x';
            pintboard();
            if(p1choice == 7 && p2choice == 7 || p1choice == 7){
            System.out.println("This spot has already been taken");
            else
                board[0][0] = 'x';
            pintboard();
            if(p1choice ==8 && p2choice == 8 || p1choice == 8){
            System.out.println("This spot has already been taken");
            else
                board[1][0] = 'x';
            pintboard();
            if(p1choice == 9 && p2choice == 9 || p1choice == 9){
            System.out.println("This spot has already been taken");
            else
                board[2][0] = 'x';
            pintboard();
        public void p2turn()
            System.out.println("Pick an area to place an O");
            int p2choice = p2choice.nextInt();
            if(p2choice == 1 && p1choice == 1 || p2choice == 1){
            System.out.println("This spot has already been taken");
            else
                board[0][2] = 'o';
            pintboard();
            if(p2choice == 2 && p1choice == 2 || p2choice == 2){
            System.out.println("This spot has already been taken");
            else
                board[1][2] = 'o';
            pintboard();
            if(p2choice == 3 && p1choice == 3 || p2choice == 3){
            System.out.println("This spot has already been taken");
            else
                board[2][2] = 'o';
            pintboard();
            if(p2choice == 4 && p1choice == 4 || p2choice == 4){
            System.out.println("This spot has already been taken");
            else
                board[0][1] = 'o';
            pintboard();
            if(p2choice == 5 && p1choice == 5 || p2choice == 5){
            System.out.println("This spot has already been taken");
            else
                board[1][1] = 'o';
            pintboard();
            if(p2choice == 6 && p1choice == 6 || p2choice == 6){
            System.out.println("This spot has already been taken");
            else
                board[2][1] = 'o';
            pintboard();
            if(p2choice == 7 && p1choice == 7 || p2choice == 7){
            System.out.println("This spot has already been taken");
            else
                board[0][0] = 'o';
            pintboard();
            if(p2choice == 8 && p1choice == 8 || p2choice == 8){
            System.out.println("This spot has already been taken");
            else
                board[1][0] = 'o';
            pintboard();
            if(p2choice == 9 && p1choice == 9 || p2choice == 9){
            System.out.println("This spot has already been taken");
            else
                board[2][0] = 'o';
            pintboard();
        public void pintboard()
        {

    Anyway the answer is that you are trying to create an array of char as there is no such thing as a board[3][3].
    One of the best tools a programmer can do is learn how to break a big problem into little problems and work on each little problem in isolation, and then when finished combining the solutions together into the final program. You big mistake that I see here is trying to bite off more than you can chew: trying to create a whole functioning interactive program from just one class. Why give yourself a task that would be difficult even for an experienced java programmer? I suggest that you break this down into logical parts and try to solve the smaller problems before worrying about the whole. For instance, if I were doing something like this, I'd create a class called TTTBoard that encapsulated the tic tac toe board and nothing but the board. I'd think of it as an entity. When I wanted the current state of the board, I'd query the board via a method such as getCurrentState. I'd have methods for checking if position is free, for placing an x/o in a spot, for checking for win, etc... Then I'd create a user interface class where I'd give the users a choice and get their responses. I'd probably create a Game class to control it all. While this all seems daunting, you are trying to do essentially the same thing, but all in one huge class. My recommendation: study OOPs and learn to do it the smart way. Good luck.

Maybe you are looking for