将 Rectangle.widthProperty() 绑定到其父宽度不起作用

Binding Rectangle.widthProperty() to its parent width does not work

我想在 BorderPane 的中间放置一个带有红色矩形的 HBox,并且我希望该矩形与其容器(HBox)一起增大或缩小。 这是我的代码:

public class Test extends Application {

    @Override
    public void start(Stage primaryStage) {
        BorderPane borderPane = new BorderPane();
        HBox hBox = new HBox();

        hBox.setAlignment(Pos.CENTER);

        Rectangle rect = new Rectangle(hBox.getWidth(),50);
        rect.setFill(Color.RED);
        rect.widthProperty().bind(hBox.widthProperty().subtract(20));

        hBox.getChildren().add(rect);

        borderPane.setCenter(hBox);     

        Scene scene = new Scene(borderPane, 900, 600, Color.WHITE);

        primaryStage.setScene(scene);
        primaryStage.show();

    }

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

但是没用。当我慢慢调整我的框架时,它起作用了,然而,当我快速调整我的框架时,矩形不在中间(也不相同大小)并且当我们最小化和最大化框架时我们可以看到相同的东西。

我不明白为什么它不起作用。

这是正在发生的事情:

rect 在布局期间被要求提供 preferred/minimum/maximum 宽度时,它会回复其当前宽度,即调整大小之前的宽度,因为那时 hBox 尚未调整大小.结果,hBox 的最小宽度被报告为其当前宽度减去 20。因此,当您缩小 window 时,hBox 的大小仍将调整为其先前的宽度减去20.

有很多方法可以解决这个问题,但更准确的答案取决于您要做什么,并且可能涉及使用 Region 而不是 Rectangle,或者覆盖矩形父级的 layoutChildren 方法。

这是一种接近于您现在所拥有的方法。它定义了一个 可调整大小的矩形 并将其最小宽度覆盖为 0.0,因此它允许缩小 HBox 的尺寸。

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

public class RectangleAutosize extends Application {

    static class ResizableRectangle extends Rectangle {
        ResizableRectangle(double w, double h) {
            super(w, h);
        }

        @Override
        public boolean isResizable() {
            return true;
        }

        @Override
        public double minWidth(double height) {
            return 0.0;
        }
    }

    @Override
    public void start(Stage primaryStage) {
        BorderPane borderPane = new BorderPane();
        HBox hBox = new HBox();

        hBox.setAlignment(Pos.CENTER);

        Rectangle rect = new ResizableRectangle(hBox.getWidth(),50);
        rect.setFill(Color.RED);
        rect.widthProperty().bind(hBox.widthProperty().subtract(20));

        hBox.getChildren().add(rect);

        borderPane.setCenter(hBox);

        Scene scene = new Scene(borderPane, 900, 600, Color.WHITE);

        primaryStage.setScene(scene);
        primaryStage.show();

    }

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