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

时间:2015-01-05 00:22:23

标签: java javafx

我的中心有一个带有Canvas的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)大的相同大小。我该怎么做?

1 个答案:

答案 0 :(得分:3)

问题是您的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放在最里面,应用了一些背景颜色,这样你就可以看到发生了什么。