首页 > 解决方案 > 只有最后一个 StackPane 呈现在屏幕上(JavaFX)

问题描述

我正在尝试在棋盘上显示一个带有多个皇后的棋盘,但它只显示其中一个。我有一个二维int数组,我穿过它,只想在占用的正方形上渲染一个女王。

public class Test5 extends Application {
    @Override
    public void start(Stage primaryStage) {

        Label Queen = new Label("Q");
        Queen.setTextFill(Color.web("#0076a3"));
        Queen.setFont(new Font(30));

        GridPane root = new GridPane();
        Random random = new Random();
        primaryStage.setScene(new Scene(root, 1000, 1000));

        int[][] b = {
            {0, 0, 1, 1, 1, 0, 0, 1, 0, 1},
            {0, 0, 1, 1, 1, 0, 0, 1, 0, 1},
            {0, 0, 1, 1, 1, 0, 0, 1, 0, 1},
            {0, 0, 1, 1, 1, 0, 0, 1, 0, 1},
            {0, 0, 1, 1, 1, 0, 0, 1, 0, 1},
            {0, 0, 1, 1, 1, 0, 0, 1, 0, 1},
            {0, 0, 1, 1, 1, 0, 0, 1, 0, 1},
            {0, 0, 1, 1, 1, 0, 0, 1, 0, 1},
            {0, 0, 1, 1, 1, 0, 0, 1, 0, 1},
            {0, 0, 1, 1, 1, 0, 0, 1, 0, 1},
        };



        final Animation animation = new Transition() {
            {
                setCycleDuration(Duration.INDEFINITE);
            }

            protected void interpolate(double frac) {


                //Iterate over loop and whenever a position is occupied add Queen to that particular StackPane
                for(int i = 0; i < b.length; i++) {
                    for(int j = 0; j < b.length; j++) {
                        if(b[i][j] == 1) {
                            StackPane place = (StackPane)root.getChildren().get(i * 10 + j);
                            place.getChildren().add(Queen);
                        }
                    }
                }

                try {
                    Thread.sleep(2000);
                }
                catch(Exception e) {

                };
            }

        }; 


        for (int row = 0; row < 10; row++) {
            for (int col = 0; col < 10; col ++) {
                StackPane square = new StackPane();
                String color ;
                if ((row + col) % 2 == 0) {
                    color = "white";
                } else {
                    color = "black";
                }


                square.setStyle("-fx-background-color: "+color+";"); 



                root.add(square, col, row);



            }
        }
        for (int i = 0; i < 10; i++) {
            root.getColumnConstraints().add(new ColumnConstraints(10, Control.USE_COMPUTED_SIZE, Double.POSITIVE_INFINITY, Priority.ALWAYS, HPos.CENTER, true));
            root.getRowConstraints().add(new RowConstraints(10, Control.USE_COMPUTED_SIZE, Double.POSITIVE_INFINITY, Priority.ALWAYS, VPos.CENTER, true));
        }




        animation.play();

        primaryStage.show();
    }


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

标签: javajavafx

解决方案


推荐阅读