Just some guy
Just some guy

Reputation: 1959

JavaFX - Updating size of BorderPane after modifying size of child node

I have a BorderPane with a Canvas in its center and I want the BorderPane to always wrap around the canvas when I change the canvas's size. Take for example this code:

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);}

I want the BorderPane to change its size after I call the setWidth and setHeight methods on canvas, but it just stays the same size as if the canvas was still (10,10) big. How do I do this?

Upvotes: 0

Views: 1109

Answers (1)

eckig
eckig

Reputation: 11154

The problem is that your BorderPane is the root of your applications Scene. The Scenes root container will not (at least not automatically) grow larger that its containing Scene.

Look at this example application:

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();
    }
}

I stacked two BorderPanes together and put the Canvas on the innermost, applied some background colors so you can see what is happening.

Upvotes: 4

Related Questions