繁体   English   中英

JavaFX-修改子节点的大小后更新BorderPane的大小

[英]JavaFX - Updating size of BorderPane after modifying size of child node

我有一个以画布为中心的BorderPane,并且我希望BorderPane在更改画布的尺寸时始终包裹在画布上。 以下面的代码为例:

public class Test extends Application {

    public void start(Stage primaryStage) {
        BorderPane root = new BorderPane();

        Canvas canvas = new Canvas(10, 10);
        root.setCenter(canvas);

        Scene s = new Scene(root);

        primaryStage.setScene(s);
        primaryStage.show();

        canvas.setWidth(100);
        canvas.setHeight(100);
    }

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

我希望BorderPane在画布上调用setWidth和setHeight方法后更改其大小,但它的大小与画布仍然是(10,10)大一样。 我该怎么做呢?

问题在于您的BorderPane是应用程序Scene的根。 Scene的根容器不会(至少不会自动)变得大于包含它的Scene

看一下这个示例应用程序:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {

        Canvas canvas = new Canvas(0, 0);
        Button button = new Button("test");
        button.setOnAction(ev -> {
            canvas.setWidth(canvas.getWidth() + 10);
            canvas.setHeight(canvas.getHeight() + 10);
            canvas.getGraphicsContext2D().clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
            canvas.getGraphicsContext2D().fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
        });

        BorderPane canvasBorderPane = new BorderPane(canvas);
        canvasBorderPane.setPadding(new Insets(10));
        canvasBorderPane.setBackground(new Background(new BackgroundFill(Color.RED, new CornerRadii(0), Insets.EMPTY)));

        BorderPane root = new BorderPane(canvasBorderPane);
        root.setPadding(new Insets(10));
        root.setBackground(new Background(new BackgroundFill(Color.BLUE, new CornerRadii(0), Insets.EMPTY)));
        root.setBottom(button);
        Scene scene = new Scene(root, 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

我将两个BorderPane堆叠在一起,并将Canvas放在最里面,应用了一些背景颜色,以便您可以看到正在发生的情况。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM