Jordan Georgiadis
Jordan Georgiadis

Reputation: 331

JavaFx Error when passing array in root.getChildren().add()

in the code below when i use only the line 54 ( line 55 comment ) , it works fine . But when i execute with line 55 in action , i get that error

Caused by: java.lang.IllegalArgumentException: Children: duplicate children added: parent = Pane@16d2d0b

    Image white = new Image("/javafxapplication1/white.png");
    ImageView whiteView = new ImageView(white);

    Image red = new Image("/javafxapplication1/red.png");
    ImageView redView = new ImageView(red);

    ImageView[] whiteArray = new ImageView[3];
    ImageView[] redArray = new ImageView[3];

    //the points of columns int the board map
    int[][] whitepoints={{54,27},{235,27},{417,27}};
    int[][] redpoints={{145,27},{325,27},{507,27}};

            whiteArray[0]=whiteView;
            whiteArray[0].setLayoutX(whitepoints[0][0]);
            whiteArray[0].setLayoutY(whitepoints[0][1]);

            whiteArray[1]=whiteView;
            whiteArray[1].setLayoutX(whitepoints[1][0]);
            whiteArray[1].setLayoutY(whitepoints[1][1]);

    Pane root = new Pane();

    imgView.fitWidthProperty().bind(primaryStage.widthProperty());
    imgView.fitHeightProperty().bind(primaryStage.heightProperty());
    root.getChildren().add(imgView);

    54!!! root.getChildren().add(whiteArray[0]);
    55!!! root.getChildren().add(whiteArray[1]);

    Scene scene = new Scene(root);

    primaryStage.setTitle("Backgammon!");
    primaryStage.setScene(scene);
    primaryStage.show();

Thanks !!!

Upvotes: 0

Views: 578

Answers (1)

James_D
James_D

Reputation: 209418

In your code, whiteArray[0] and whiteArray[1] both refer to the same instance of ImageView (the one you previously called whiteView). You can't add the same ImageView to the scene graph twice.

I think what you are trying to do is share the same Image between two different ImageViews:

Image white = new Image("/javafxapplication1/white.png");

Image red = new Image("/javafxapplication1/red.png");

// maybe the same problem with this in code you haven't shown???
ImageView redView = new ImageView(red);

ImageView[] whiteArray = new ImageView[3];
ImageView[] redArray = new ImageView[3];

//the points of columns int the board map
int[][] whitepoints={{54,27},{235,27},{417,27}};
int[][] redpoints={{145,27},{325,27},{507,27}};

whiteArray[0]=new ImageView(white);
whiteArray[0].setLayoutX(whitepoints[0][0]);
whiteArray[0].setLayoutY(whitepoints[0][1]);

whiteArray[1]=new ImageView(white);
whiteArray[1].setLayoutX(whitepoints[1][0]);
whiteArray[1].setLayoutY(whitepoints[1][1]);

Pane root = new Pane();

imgView.fitWidthProperty().bind(primaryStage.widthProperty());
imgView.fitHeightProperty().bind(primaryStage.heightProperty());
root.getChildren().add(imgView);

root.getChildren().add(whiteArray[0]);
root.getChildren().add(whiteArray[1]);

Upvotes: 1

Related Questions