0

Firstly, sorry for my English :(

I'm reading "Introduction to Java Programming" and stuck in a exercise: Write a program that displays a tic-tac-toe board. A cell may be X, O, or empty. What to display at each cell is randomly decided.

Below is my code

public class TictactoeBoard extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
    GridPane pane = new GridPane();     
    Image ximage = new Image("x.gif");
    Image oimage = new Image("o.gif");
    ImageView xImageView = new ImageView(ximage);
    ImageView oImageView = new ImageView(oimage);

    for(int i = 0; i < 3; i++) {
           for(int j = 0; j < 3; j++) {
            int random = (int)(Math.random() * 2);
            if(random == 0) {
             pane.add(xImageView, j, i);
            } else {
             pane.add(oImageView, j, i);
            }
           }
          }

    Scene scene = new Scene(pane);
    primaryStage.setTitle("Tic-tac-toe Board");
    primaryStage.setScene(scene);
    primaryStage.show();
    primaryStage.setResizable(false);
}

public static void main(String[] args) {
    Application.launch(args);
}

It stuck at pane.add in the for loop. It get this error: http://pastebin.com/TB9kLhrZ

I tried not to use for loop and manually add (for example)

pane.add(oImageView, 0, 2);
pane.add(xImageView, 1, 3);

The application work perfectly. Can someone show me why this problem happen and how to fix it? Thanks you very much!

dangxunb
  • 3
  • 1
  • 4
  • It always amazes me how Americans have such a silly name for noughts and crosses :) – NickJ Jun 17 '15 at 08:52
  • Look at this answer as well - http://stackoverflow.com/questions/25357793/how-to-add-imageviews-to-gridpane-using-a-forloop – Sathish Jun 17 '15 at 09:05

1 Answers1

1

You can add same view only once to some parent. So you need to create new ImageView for each cell, like this:

for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
        int random = (int)(Math.random() * 2);
        if(random == 0) {
            pane.add(new ImageView(ximage), j, i);
        } else {
           pane.add(new ImageView(oimage), j, i);
        }
    }
}
varren
  • 14,551
  • 2
  • 41
  • 72
  • Thanks you. The book didn't tell me that important thing! It's took me about 4hour to google :( – dangxunb Jun 17 '15 at 09:08
  • 1
    @dangxunb The [documentation for `Node`](http://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html) has some very important information, including "A node may occur at most once anywhere in the scene graph.". You should probably read through the docs for `Node`, `Scene`, and `Application` as a minimum. – James_D Jun 17 '15 at 13:37