javaFX:move shapes with absolute coordinates using

2019-07-25 21:09发布

问题:

I am implementing a merge sort animation using javaFX. I want to use absolute coordinates to move shapes. I use setToX() and setToY() of Translatetransition(). However, these shapes are in a HBox with fixed spacing. I try to move them into different place but it does not work. setToX() and setToY() use HBox as a reference. Shapes are always with a fixed spacing and the sequence of shapes do not change. I use getLayoutX() and getLayoutY() to get absolute coordinates. Who can help me??

These are related code:

HBox hBox = new HBox(20);

    hBox.setAlignment(Pos.CENTER);
    hBox.setPadding(new Insets(0,0,0,0));
    ArrayList<StackPane> list = new ArrayList<>();
    Random random = new Random(5);
    for (int i = 0; i < 12; i++) {
        int num = random.nextInt(10);
        Rectangle rectangle = new Rectangle(40, (num * 10) + 50);
        rectangle.setFill(Color.valueOf("#0000FF"));
        Text text = new Text(String.valueOf(num));
        StackPane stackPane = new StackPane();
        stackPane.setPrefSize(rectangle.getWidth(), rectangle.getHeight());
        stackPane.setId(String.valueOf(num));
        stackPane.getChildren().addAll(rectangle, text);
        StackPane.setAlignment(text,Pos.TOP_CENTER);
        stackPane.setAlignment(Pos.TOP_CENTER);
        list.add(stackPane);
    }


    hBox.getChildren().addAll(list);

    BorderPane borderPane = new BorderPane();
    borderPane.setCenter(hBox);

This is tranlation function

 private TranslateTransition AddtoOriginal(StackPane sp, double speed,int X,int Y){

    TranslateTransition t = new TranslateTransition();
    t.setNode(sp);
    t.setDuration(Duration.millis(speed));
    t.setToX(X);
    t.setToY(Y);
    return t;

}

This is to save absolute coordinates

 Scene scene = new Scene(borderPane, 1000, 800);
    primaryStage.setTitle("Sorting");
    primaryStage.setResizable(false);
    primaryStage.setScene(scene);
    primaryStage.show();

    for (int i = 0; i < 12; i++) {
        int centerx = (int) list.get(i).getLayoutX();
        int centery = (int) list.get(i).getLayoutY();
        CenterX.add(i,centerx);
        CenterY.add(i,centery);
        System.out.println(centerx);
        System.out.println(centery);
    }

回答1:

Pls Using the Group or Pane as the container instead of Hbox. HBox has its layout out policy and it doesn't support the absolute coordinate.