gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:54:40 30 4
gpt4 key购买 nike

我想在 BorderPane 中间放置一个带有红色矩形的 HBox,并且我希望该矩形随其容器( H盒)。这是我的代码:

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 在布局期间被要求提供首选/最小/最大宽度时,它会回复其当前宽度,即调整大小之前的宽度,因为那时 hBox 已经尚未调整大小。因此,hBox 的最小宽度为其当前宽度减去 20。因此,当您缩小窗口时,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);
}
}

关于java - 将 Rectangle.widthProperty() 绑定(bind)到其父宽度不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28908800/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com