(Displaying a TicTacToe board) Display a frame that contains nine labels. A labelmay display a cross image icon, a not image icon, or nothing, as shown in Figure 12.18(a). What to display is randomly decided. Use the Math.random()method to generate an integer0,1, or 2, which corresponds to displaying across image icon, a not image icon, or nothing. The cross and not imagescanbe obtained from the cross.gif and not.gif files in the image directory onthe Companion Website.
时间: 2023-07-02 19:06:29 浏览: 92
A robust photometric calibration framework for projector-camera display system
Here's the code for displaying a TicTacToe board with randomly generated crosses, nots, or nothing in each square:
```
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class TicTacToeBoard extends JFrame {
public TicTacToeBoard() {
// Set up the frame
setTitle("Tic Tac Toe Board");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 3));
// Create an array of labels for the board
JLabel[] board = new JLabel[9];
// Create a random number generator
Random rand = new Random();
// Loop through the board array and add labels with random icons
for (int i = 0; i < board.length; i++) {
ImageIcon icon = null;
int num = rand.nextInt(3);
if (num == 0) {
icon = new ImageIcon("image/cross.gif");
} else if (num == 1) {
icon = new ImageIcon("image/not.gif");
}
board[i] = new JLabel(icon);
add(board[i]);
}
// Pack and display the frame
pack();
setVisible(true);
}
public static void main(String[] args) {
new TicTacToeBoard();
}
}
```
Note that this code assumes that the `cross.gif` and `not.gif` files are located in a directory called `image` in the same directory as the compiled Java class. Adjust the file paths accordingly if necessary.
阅读全文