Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Tic Tac Toe GUI program

  1. #1
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Tic Tac Toe GUI program

    So this is for my Computer Programming II class that I'm taking in college and I'm completely lost. I have my GUI all set up, and everything is working except for finding a win. Any help at all would be appreciated. Thanks in advance

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
     
    /**
     *
     * @author TSPARR
     */
    public class TicTacToeFrame extends JFrame
    {
        private static final GridLayout LAYOUT = new GridLayout(3,3);
        private static final int HEIGHT = 500;
        private static final int WIDTH = 500;
     
        private JButton buttons[] = new JButton[10], quitBtn;
        private JPanel wholePanel, boardPanel, titlePanel;
        private JLabel title;
        private int turns = 0;
        private String letter = "";
        private boolean win = false;
     
     
        public TicTacToeFrame()
        {
           createQuitButton();
           createTitlePanel();
           createBoardPanel();
           createWholePanel();
           findHorzWins();
           findVertWins();
           findDiagWins();
           showResults();
     
            //Gets the width of the screen
            Toolkit kit = Toolkit.getDefaultToolkit();
            Dimension screenSize = kit.getScreenSize();
            int screenHeight = screenSize.height;
            int screenWidth = screenSize.width;
     
            //Sets the screen size to half the height and width of the screen, and centers it
            setSize(WIDTH, HEIGHT);
            setLocation(screenWidth / 4, screenHeight / 4);
        }
     
        private void createQuitButton()
        {
            quitBtn = new JButton("-- Quit --");
            quitBtn.setFont(new Font(Font.SERIF, 0, 24));
     
            class QuitListener implements ActionListener
            {
     
                @Override
                public void actionPerformed(ActionEvent ae) 
                {
                    System.exit(0);
                }
     
           }
     
            ActionListener quitListener = new QuitListener();
            quitBtn.addActionListener(quitListener);
        }
     
        private void createTitlePanel()
        {
            title = new JLabel("Welcome to my Tic Tac Toe Game!");
            titlePanel = new JPanel();
            title.setFont(new Font(Font.SERIF, 0, 30));
            titlePanel.add(title);
        }
     
        private void createBoardPanel()
        {
            boardPanel = new JPanel();
            boardPanel.setLayout(LAYOUT);
     
            class ButtonListener implements ActionListener
            {
     
                @Override
                public void actionPerformed(ActionEvent ae) 
                {
                    turns++;
                    if(turns % 2 == 0)
                    {
                        letter = "O";
                    }
                    else {
                        letter = "X";
                    }
     
                    JButton pressedButton = (JButton)ae.getSource();
                    pressedButton.setText(letter);
                    pressedButton.setEnabled(false);
                }
     
            }
     
            ActionListener buttonListener = new ButtonListener();
            for(int i=1; i<=9; i++)
            {
                buttons[i] = new JButton("");
                buttons[i].setFont(new Font(Font.SERIF, 0, 24));
                buttons[i].addActionListener(buttonListener);
                boardPanel.add(buttons[i]);
            }
        }
     
        private void createWholePanel()
        {
            wholePanel = new JPanel();
            wholePanel.setLayout(new BorderLayout());
            wholePanel.add(titlePanel, BorderLayout.NORTH);
            wholePanel.add(boardPanel, BorderLayout.CENTER);
            wholePanel.add(quitBtn, BorderLayout.SOUTH);
            add(wholePanel);
        }
     
        public void findHorzWins()
        {
            if (buttons[1].getText().equals(buttons[2].getText()) && buttons[2].getText().equals(buttons[3].getText()) && buttons[1].getText().equals("")==false)
            {
                win=true;
            }
     
            else if (buttons[4].getText().equals(buttons[5].getText()) && buttons[5].getText().equals(buttons[6].getText()) && buttons[4].getText().equals("")==false)
            {
                win=true;
            }
     
            else if (buttons[7].getText().equals(buttons[8].getText()) && buttons[8].getText().equals(buttons[9].getText()) && buttons[7].getText().equals("")==false)
            {
                win=true;
            }
        }
     
        public void findVertWins()
        {
            if (buttons[1].getText().equals(buttons[4].getText()) && buttons[4].getText().equals(buttons[7].getText()) && buttons[1].getText().equals("")==false)
            {
                win=true;
     
            }
     
            else if (buttons[2].getText().equals(buttons[5].getText()) && buttons[5].getText().equals(buttons[8].getText()) && buttons[2].getText().equals("")==false)
            {
                win=true;
     
            }
     
            else if (buttons[3].getText().equals(buttons[6].getText()) && buttons[6].getText().equals(buttons[9].getText()) && buttons[3].getText().equals("")==false)
            {
                win=true;
     
            }
        }
     
        public void findDiagWins()
        {
            if (buttons[1].getText().equals(buttons[5].getText()) && buttons[5].getText().equals(buttons[9].getText()) && buttons[1].getText().equals("")==false)
            {
                win=true;
            }
     
            else if (buttons[3].getText().equals(buttons[5].getText()) && buttons[5].getText().equals(buttons[7].getText()) && buttons[3].getText().equals("")==false)
            {
                win=true;
            }
        }
     
        public void showResults()
        {
            while(turns>=5)
            {
                findHorzWins();
                findVertWins();
                findDiagWins();
     
                if (win==true)
                {
                    JOptionPane.showMessageDialog(null, letter + " is the winner! Congratulations!");
                    System.exit(0);
                }
     
                else if (turns==9 && win==false)
                {
                    JOptionPane.showMessageDialog(null, "The game is a tie.");
                    System.exit(0);
                }
            }
        }           
    }


    import javax.swing.JFrame;
     
    /**
     *
     * @author TSPARR
     */
    public class TicTacToeRunner {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) 
        {
            JFrame frame = new TicTacToeFrame();
            frame.setTitle("Tic Tac Toe Game");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
     
        }
    }


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,707
    Thanks
    25
    Thanked 338 Times in 313 Posts

    Default Re: Tic Tac Toe GUI program

    I have a question first out of curiosity: What is in buttons[0]? I don't think you ever reference it.

    Now, your problem is with this:
    public void showResults()
        {
            while(turns>=5)
            {
                findHorzWins();
                findVertWins();
                findDiagWins();

    In these methods, you are setting the win variable to true if the correct criteria match. That is all fine, but by calling each of those methods after one another, you are overriding the win variable, meaning the only result that will matter is what your findDiagWins() method does. My guess is that if you set it up so you win diagonally, you will find that it works. The best way to fix your problem, given the way you wrote your code, is to check if win==true after each of those method calls. If it is true, don't perform the next operation.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Tic Tac Toe GUI program

    buttons[0] is I have to assume empty or null. I set it up this way so that my numbers go 1-9, instead of 0-8. It was more of a personal preference because it makes it easier to picture in my head.

    Now, I rewrote my showResults() method (possibly in the least efficient manner, but as more of a test based on what you said), but it still isn't working. I'm not sure if I'm maybe misunderstanding something entirely as to how to check for wins, or what.

    public void showResults()
        {
            while(turns>=5)
            {
                findHorzWins();
     
                if (win==true)
                {
                    JOptionPane.showMessageDialog(null, letter + " is the winner! Congratulations!");
                    System.exit(0);
                }
     
                else if (turns==9 && win==false)
                {
                    JOptionPane.showMessageDialog(null, "The game is a tie.");
                    System.exit(0);
                }
     
                findVertWins();
     
                if (win==true)
                {
                    JOptionPane.showMessageDialog(null, letter + " is the winner! Congratulations!");
                    System.exit(0);
                }
     
                else if (turns==9 && win==false)
                {
                    JOptionPane.showMessageDialog(null, "The game is a tie.");
                    System.exit(0);
                }
     
                findDiagWins();
     
                if (win==true)
                {
                    JOptionPane.showMessageDialog(null, letter + " is the winner! Congratulations!");
                    System.exit(0);
                }
     
                else if (turns==9 && win==false)
                {
                    JOptionPane.showMessageDialog(null, "The game is a tie.");
                    System.exit(0);
                }
            }
        }

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,707
    Thanks
    25
    Thanked 338 Times in 313 Posts

    Default Re: Tic Tac Toe GUI program

    Ok, well that would probably quit after the first check if turns==9, since it will just hit the else statement.

    My suggestion is by saying:
    findHorzWins();
    if(!win)
         findVertWins();
    if(!win)
         findDiagWins();
     
    if (win==true)
                {
                    JOptionPane.showMessageDialog(null, letter + " is the winner! Congratulations!");
                    System.exit(0);
                }
     
                else if (turns==9 && win==false)
                {
                    JOptionPane.showMessageDialog(null, "The game is a tie.");
                    System.exit(0);
                }

    Tell me more about how its not working. Is it waiting until the game finishes, or ending early?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. #5
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Tic Tac Toe GUI program

    I can click every button and never have the JOptionPane message show up. The only way to exit the GUI is to hit the quit button.

  6. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,707
    Thanks
    25
    Thanked 338 Times in 313 Posts

    Default Re: Tic Tac Toe GUI program

    Ah, that's different than I was thinking was happening. I thought the win just wouldn't work. Ok, well if neither win or lose ever shows up, that means we are not reevaluating the showResults() method after every turn. At the end of your ButtonListener.actionPerformed(...) method, add the statement: showResults();
    You made the call in the very beginning of your program, but not after each time the button is pressed.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  7. The Following User Says Thank You to aussiemcgr For This Useful Post:

    TSPARR (May 7th, 2012)

  8. #7
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,707
    Thanks
    25
    Thanked 338 Times in 313 Posts

    Default Re: Tic Tac Toe GUI program

    Also, you have an infinite loop in your showResults() method. The while loop is unnecessary. My suspicion is that you don't understand how Listeners work (perhaps maybe even a thread problem, not sure what this would be considered).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  9. #8
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Tic Tac Toe GUI program

    The only issue with what you're suggesting is that as part of the assignment, I'm only supposed to check for results after the 5th turn. This is because that is when it is first possible for a win to be had.


    Edit: Would it be possible to put these into my "if" statements while getting wins?

    public void findVertWins()
        {
            if (buttons[1].getText().equals(buttons[4].getText()) && buttons[4].getText().equals(buttons[7].getText()) && buttons[1].getText().equals("")==false && turns>=5)
            {
                win=true;
     
            }
     
            else if (buttons[2].getText().equals(buttons[5].getText()) && buttons[5].getText().equals(buttons[8].getText()) && buttons[2].getText().equals("")==false && turns>=5)
            {
                win=true;
     
            }
     
            else if (buttons[3].getText().equals(buttons[6].getText()) && buttons[6].getText().equals(buttons[9].getText()) && buttons[3].getText().equals("")==false && turns>=5)
            {
                win=true;
     
            }
        }
    Last edited by TSPARR; May 7th, 2012 at 06:07 PM.

  10. #9
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Tic Tac Toe GUI program

    I just wanted to point out that my additions of "&& turns>=5" still compiles and the game works right. I just don't know if it really fits the spirit of: "The game should check for wins after each move starting with the 5th and should check for a tie (9th move)."

  11. #10
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,707
    Thanks
    25
    Thanked 338 Times in 313 Posts

    Default Re: Tic Tac Toe GUI program

    You can meet that requirement by changing the while(turns>=5) in your showResults() method to if(turns>=5).

    Your code with your while loop is under the assumption that you can make the showResults() method loop forever while the buttons are being pressed. In a single-threaded program, that is not the case (and even if it was a multi-threaded program, you would probably get an exception for referencing the turns variable on two threads at the same time). What would happen, with the while loop there, is that after the 5th turn, your entire program will lock up and crash. The reason is because you would be stuck in the while loop. By replacing the while loop with the if statement, you are making sure that the showResults() method will run, at most, once per turn (which is the desired behavior).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  12. The Following User Says Thank You to aussiemcgr For This Useful Post:

    TSPARR (May 7th, 2012)

  13. #11
    Junior Member
    Join Date
    May 2012
    Posts
    6
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Tic Tac Toe GUI program

    Ah....that makes so much more sense to me now. Thank you so much for your help, is there some way I can mark this thread as solved?


    Edit: Got it

Similar Threads

  1. Program to launch and mirror another program
    By hayate in forum Java Theory & Questions
    Replies: 13
    Last Post: March 9th, 2012, 12:47 AM
  2. Help with class program!!! STUCK! Program not doing what I Want!!!
    By sketch_flygirl in forum What's Wrong With My Code?
    Replies: 7
    Last Post: April 4th, 2011, 08:29 AM