(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 18:20:19 浏览: 47
以下是一个实现这个功能的示例代码:
```java
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TicTacToeBoard extends JFrame {
public TicTacToeBoard() {
setLayout(new GridLayout(3, 3)); // 设置布局为3行3列的网格布局
// 随机生成每个标签应该显示的内容
for (int i = 0; i < 9; i++) {
int random = (int) (Math.random() * 3); // 生成0,1,2之间的整数
JLabel label = new JLabel(); // 创建标签对象
if (random == 0) {
ImageIcon icon = new ImageIcon("image/cross.gif"); // 创建一个显示cross.gif的图标对象
label.setIcon(icon); // 设置标签的图标为cross.gif
} else if (random == 1) {
ImageIcon icon = new ImageIcon("image/not.gif"); // 创建一个显示not.gif的图标对象
label.setIcon(icon); // 设置标签的图标为not.gif
}
// 其它情况标签不显示图标
add(label); // 将标签添加到窗口中
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null); // 居中显示窗口
setVisible(true);
}
public static void main(String[] args) {
new TicTacToeBoard();
}
}
```
在这个示例代码中,我们创建了一个 `JFrame` 对象,并将其布局设置为 3 行 3 列的网格布局。然后,我们使用一个循环随机生成每个标签应该显示的内容,并将其添加到窗口中。如果随机数是 0,则显示 cross.gif 的图标;如果随机数是 1,则显示 not.gif 的图标;否则标签不显示任何图标。最后,我们将窗口设置为可见并居中显示。