在 root.getChildren().add() 中传递数组时出现 JavaFx 错误

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

在下面的代码中,当我只使用第 54 行(第 55 行注释)时,它工作正常。但是当我执行第 55 行时,我得到了那个错误

原因:java.lang.IllegalArgumentException:Children:重复 children 添加: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();

谢谢!!!

在您的代码中,whiteArray[0]whiteArray[1] 都指的是 ImageView 的同一个实例(您之前称为 whiteView 的实例)。您不能将相同的 ImageView 添加到场景图中两次。

我认为您要做的是在两个不同的 ImageView 之间共享相同的 Image

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]);