Sunday, December 09, 2007


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:
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.

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());
case 1:
add(new JLabel(cross));
case 2:
add(new JLabel(not));

public static void main(String[] args) {
DisplayTicTacToe frame = new DisplayTicTacToe();
frame.setTitle("Display Tic Tac Toe");
frame.setSize(225, 225);

No comments: