JavaFX:将子项添加到root父项后自动调整阶段

Ark*_*ost 6 javafx javafx-2

当我点击时,我需要显示一个Panel额外的选项,但我不知道如何实现这种行为.将面板添加到root时未调整大小的问题.SceneButtonStageVBox

我编写了简单的代码来演示这个问题.

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();
   }
}
Run Code Online (Sandbox Code Playgroud)

我想我需要调用一些方法来通知root容器进行布局,但我尝试的所有方法都没有给我带来理想的结果.

jew*_*sea 27

节目作品

您的程序几乎按照您的预期工作(当您单击"添加标签"按钮时,会在场景中添加新标签).

为什么你看不到它的工作原理

您无法看到新添加的标签,因为默认情况下舞台的大小适合场景的初始内容.向场景添加更多区域时,舞台不会自动调整大小以包含新区域.

该怎么做才能看到它有效

添加标签后手动调整舞台窗口的大小.

要么

设置场景的初始大小,以便您可以看到新添加的标签.

stage.setScene(new Scene(root, 200, 300));
Run Code Online (Sandbox Code Playgroud)

要么

添加每个新标签后,将舞台大小调整到场景.

stage.sizeToScene();
Run Code Online (Sandbox Code Playgroud)