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.
These statements will compile and execute
private ImageIcon cross = new ImageIcon("image/x.gif");
private ImageIcon not = new ImageIcon("image/o.gif");
if you have an image subfolder off the main project folder and the image subfolder is on the build path. These ImageIcons should be built in their own method, so you can handle the generated error(s) if the gifs are missing.
I read image files like this.
try {
img = ImageIO.read(new File("graphics/close_0.jpg"));
remoteController = ImageIO.read(new File("graphics/pilot.png"));
} catch (IOException e) {
e.printStackTrace();
}
That way, your code doesn't have to wait for the images to load.
If you use an integrated development environment (IDE) like Eclipse, Eclipse will generate the following statements from the code.
import java.awt.GridLayout;
import javax.swing.ImageIcon;
If you're not using an IDE, the following statements are OK. You don't want to spend a lot of time manually typing import statements.
import java.awt.*;
import javax.swing.*;