HB Node上的Java Node动态位置

时间:2016-05-04 21:25:08

标签: java javafx javafx-8

我使用某些事件在HBox上放置小矩形。当窗口没有调整大小时,它们的位置是完美的,但是当你从小到全屏时,它们的位置是错误的(当然,因为它们在放置时得到X的某个值 - 这是通过获得那个特定时刻HBox的宽度。)

问题:

如何让这些位置变得动态,所以当我调整窗口大小时,它们会保持成比例?

图片: Normal view Fullscreen

代码:

@FXML HBox tagLine; // initializes the HBox

...

public void addTag(String sort) {
    Rectangle rect = new Rectangle(20, tagLine.getHeight());
    double pos = timeSlider.getValue() / 100 * tagLine.getWidth(); // retrieves position at the moment of being called
    rect.setTranslateX(pos);
    rect.setOnMouseEntered(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            showNotification("Gemarkeerde gebeurtenis: " + sort);
        }
    });
    rect.setOnMouseExited(new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent event) {
            notificationHide.play();
        }
    });

    tagLine.getChildren().add(rect);
}

1 个答案:

答案 0 :(得分:1)

在使用问责大小翻译形状时,您需要考虑的几件事情是您需要:

  • 从中心翻译形状
  • 如果转换取决于节点的宽度,请聆听对该特定节点的更改,并相应地更改translate属性

您的实施中似乎缺少上述两点。你永远不会听HBox的宽度属性。您的计算pos也不考虑Rectangle的中心。

这是一个试图将Rectangle保持在中心的示例,无论您的HBox大小如何。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Main extends Application {

    private static final int SIDE = 40;
    private static final double DEFAULT_WIDTH = 200;
    private static final double DEFAULT_POSITION = 100;

    @Override
    public void start(Stage primaryStage) {

        Rectangle rectangle = new Rectangle(SIDE, SIDE);
        HBox root = new HBox(rectangle);
        root.setPrefWidth(DEFAULT_WIDTH);

        rectangle.translateXProperty().bind(root.widthProperty().multiply(DEFAULT_POSITION/DEFAULT_WIDTH).subtract(SIDE/2));

        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

enter image description here