Introduction to Java using NetBeans

Section 9 : Tic Tac Toe


This is an image of a Tic-Tac-Toe Board.

An array with two dimensions can be used to represent data that corresponds to a grid.

A tic-tac-toe board can be represented by a two-dimensional array with three rows and three columns





Create a Game Board


Step 1 – Create a New Application

  • Create a New Project. Choose the Java Class Library. Call the project TicTac.
  • Double-click Source Packages. From the Menu Bar, select File, New File. Now choose Java, then Java Main Class. Type TicTac for the ClassName.

Step 2 – Set Up the Playing Board


Public Class

Discussion of the Code

  • JPanel creates the outline box.
  • JButton[ ] [ ] creates nine buttons in a 2D array that is 3 x 3.
  • The other lines create buttons and text fields to be used later.


General Infomation

Method Types

public means that the method is visible and can be called from other objects of other types. Other alternatives are private, protected, package and package-private. See here for more details.

static means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.

void means that the method has no return value. If the method returned an int you would write int instead of void.



Create the Playing Board


Create the following public method

Main Class


Discussion of the Code

  • public TicTac ( ) – creates the method to draw the game board.
  • super (“Tic Tac Toe”) – creates the outer frame with the title.
  • setSize (500,600) – sets the size of the outer frame.
  • setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) – sets the program to quit running when the window is closed.
  • FlowLayout – arranges components from left to right, centering components horizontally with a five pixel gap between them.
  • GridLayout – arranges the components in a rectangular grid, where all cells are of equal size.
  • For loops – creates and adds the buttons to the GridLayout's first three rows.
  • row1.add – adds remaining components to the GridLayout.
  • add(row1) – adds the GridLayout to the FlowLayout.
  • setVisible(true) – shows the FlowLayout on the screen.
  • TicTac frame = new TicTac() – runs the screen layout class.


Adding Graphics


  • Download the graphics and place them in the TicTac folder.
  • Background graphic Background (or get your own)
  • X graphic X (or make your own)
  • O graphic O (or make your own)
  • Run the program. You should now have the screen shown below.



Create the Event File

Step 1 - Create the Event Class

  • From the Menu bar, select New, New File. Now select Java, Empty Java File.
  • Call the file TicTacEvent.

Step 2 - Create the Event


Public Class



Discussion of the Code

  • Import statements – use the classes that will be required for the program.
  • public class TicTacEvent – creates a class that responds to mouse and keyboard input by “listening.”
  • TicTac gui – associates the game board with the event.
  • New variables – created to check for a winner.
  • public TicTacEvent (TicTac in) – associates the two files to be used together.
  • For loop – initiates the winner check array.

Step 3 – Create Methods to Handle Click on each Button

Create Method for Button 1

  • Copy and paste this code eight times before the last OR create one method and pass parameters(BETTER)
  • Change the name of each method (i.e. b2)
  • Change the array values for each item (i.e. 0,1)

Discussion of the Code

  • clicks = clicks + 1 – keeps track of the number of boxes chosen.
  • If structure – puts an X on the board and declares that square to be taken.
  • Else structure – puts an O on the board and declares that square to be taken.

    Associate the File
  • Move to Public class TicTacEvent and press Alt Enter. Choose “Implement all abstract methods.”

Step 4 – Add the Action Event

  • Add the code below right after the public TicTacEvent method, (but before the last }).

Use a case or if's to call each of the methods above

Now Either modify b1 to pass parameters to determine button location or repeat the the methods (not the best way)


Discussion of the Code

  • public void actionPerformed (ActionEvent event) – tells the program what to do when a button is clicked.
  • String command = event.getActionCommand( ) – takes the button name as input from the button that is clicked.
  • switch – checks the command variable and calls the appropriate method.



Step 6 – Create a Listen Function for the Event

  • Add the following line under public class TicTac extends JFrame {

TicTacEvent tictac = new TicTacEvent(this);


  • Go to the file and add the following code after add(board);

Discussion of the Code

  • addActionListener – makes the program ready to handle mouse clicks.
  • TicTacEvent – joins the two programs to work with each other.

Step 7 – Run the Program

  • Run the program and notice that it doesn't stop when there is a winner. We will be looking at that part in the next section.



Checking for a Winner


To win the game of tic-tac-toe, a player must successfully place three of his symbols in a straight line. We will now look at how to determine if a player has done this and won the game.

Table showing the rows and columns of a matrix used for two- dimensional tic tac toe array.

Check for a Winner by Row

  • Create a new method called Winner


    Call the Winner method in each of your button methods

Discussion of Code

  • For loop – checks each colum
  • If structure – checks to see if all entries are X, or all entries are O.
  • JOptionPane.showMessageDialog – creates a pop up box declaring a winner.


Your Turn

Check for a Winner by Row

Check for a Winner Diagonally

Check for a Tie (Hint: Use clicks)

Make sure you can't click a box more than once

Use the 2 additional labels to keep track of how many wins X has and how many wins O has.

Display the win by changing the colour, drawing a line, etc.