My problem is this:
(Game: display a tic-tac-toe board) Display a frame that contains nine labels. A label may display an image icon for X or and image icon for O. What to display is randomly decided. Use the Math.random() method to generate an integer 0 or 1, which corresponds to displaying an X or O image icon. These images are in the files x.gif and o.gif
The problem I'm having is the fact that the imgaes wont show in the program. When i run it the program generates an empty frame. My guess is that there must be a problem with the location of the image files.
I have downloaded a .zip from the publisher of the book im using (Introduction to Java programming by Liang) which it seems the images should contain. But it didnt. So i found the identical .gif's online and downloaded them. Now im wondering how i set the right location.
I think the code itself should be okay. Here it is anyways.
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TicTacToe extends JFrame {
private ImageIcon cross = new ImageIcon("image/x.gif");
private ImageIcon not = new ImageIcon("image/o.gif");
public TicTacToe() {
setLayout(new GridLayout(3, 3));
for (int i = 0; i < 9; i++) {
int mode = (int) (Math.random() * 3.0);
if (mode == 0)
add(new JLabel(this.cross));
else if (mode == 1)
add(new JLabel(this.not));
else
add(new JLabel());
}
}
public static void main(String[] args) {
TicTacToe frame = new TicTacToe();
frame.setTitle("TicTacToe");
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(3);
frame.setVisible(true);
}
}
Another small question, would using this:
import java.awt.*;
import javax.swing.*;
instead of this:
import java.awt.GridLayout;
import javax.swing.ImageIcon;
Be a bad thing? I'm thinking if you think my lecturer would find it lazy to always import all instead of the separate I need.
In advance - thanks.