JavaFX: autoresize stage after adding child to root parent


Question

I need to show a Panel with an extra options in the same Scene when I click on the Button, but I've no idea how to achieve this behaviour. The problem that the Stage not resizing when I add panel to root VBox.

I've written simple code to demonstrate the problem.

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {
   public static void main(String[] args) {
       launch(args);
   }

   public void start(Stage stage) throws Exception {
       final VBox root = new VBox();
       Button button = new Button("add label");
       root.getChildren().add(button);

       button.setOnAction(new EventHandler<ActionEvent>() {
           public void handle(ActionEvent event) {
               root.getChildren().add(new Label("hello"));
           }
       });

       stage.setScene(new Scene(root));
       stage.show();
   }
}

I suppose I need to call some method to notify root container to do layout, but all methods I try haven't brought me desired results.

1
6
10/29/2013 11:48:21 PM

Accepted Answer

Program Works

Your program is working almost as you expect I think (when you click the "add label" button, a new label is added to the scene).

Why you can't see it working

You can't see the newly added label as a stage is sized by default to fit the initial content of the scene. When you add more area to the scene, the stage won't be automatically resized to encompass the new area.

What to do to see it work

Manually resize the stage window after adding a label.

OR

Set an initial size for the scene so that you can see the newly added labels.

stage.setScene(new Scene(root, 200, 300));

OR

After you add each new label, size the stage to the scene.

stage.sizeToScene();
27
10/30/2013 9:22:11 AM

just change the code

button.setOnAction(new EventHandler<ActionEvent>()
{
     public void handle(ActionEvent event)
     {
         root.getChildren().add(new Label("hello"));
         stage.sizeToScene();
     }
});

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon