Sunday, December 09, 2007

DisplayTicTacToe

Haven't posted my Java exercise answers in a while. Here's one that looks simple but is a little tricky to implement.

Note: Download the files here:
http://www.cs.armstrong.edu/liang/intro6e/book/image/cross.gif
http://www.cs.armstrong.edu/liang/intro6e/book/image/not.gif
and save them in a folder called "image" in the same folder as your class path. I'm using NetBeans, so I place it inside my Project Folder. You can specify another literal path if you wish.
12.7** (Displaying a TicTacToe board) Display a frame that contains nine labels. A label may display a cross image icon, a not image icon, or nothing. What to display is randomly decided. Use the Math.random() method to generate an integer 0, 1, or 2, which corresponds to displaying a cross image icon, a not image icon, or nothing.
DisplayTicTacToe.java

import java.awt.*;
import javax.swing.*;

public class DisplayTicTacToe extends JFrame {

private ImageIcon cross = new ImageIcon("image/cross.gif");
private ImageIcon not = new ImageIcon("image/not.gif");

public DisplayTicTacToe() {
setLayout(new GridLayout(3, 3, 3, 3));
for (int i = 0; i < 9; i++) {
int randomizer = (int) (Math.floor(Math.random() * 3));
switch (randomizer) {
case 0:
add(new JLabel());
break;
case 1:
add(new JLabel(cross));
break;
case 2:
add(new JLabel(not));
break;
}
}
}

public static void main(String[] args) {
DisplayTicTacToe frame = new DisplayTicTacToe();
frame.setTitle("Display Tic Tac Toe");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(225, 225);
frame.setVisible(true);
}
}

No comments: