Page 743 - Introduction to Programming with Java: A Problem Solving Approach
P. 743

                17.6 Tic-Tac-Toe Example 709
 /**************************************************************
*
TicTacToe.java
Dean & Dean
This program implements the game of tic-tac-toe.
When the first blank button is clicked, its label changes
to an X. Subsequent clicked blank buttons change their labels
to O and X in alternating sequence.
**************************************************************/
*
*
*
*
*
*
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TicTacToe extends JFrame
{
private boolean xTurn = true; // keeps track of whether
// it's X's turn or O's turn
//***********************************************************
public TicTacToe()
{
setTitle("Tic-Tac-Toe");
       Apago PDF Enhancer
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
// end TicTacToe constructor
//***********************************************************
}
}
// end createContents
setSize(200, 220);
// Create components and add to window.
private void createContents()
{
JButton button; // re-instantiate this button and use
// to fill entire board
setLayout(new GridLayout(3, 3));
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
button = new JButton();
button.addActionListener(new Listener());
add(button);
} // end for j
} // end for i
Figure 17.7a TicTacToe program—part A














































   741   742   743   744   745