Javafx 2 JavaFX:将子级添加到根父级后自动调整阶段

Javafx 2 JavaFX:将子级添加到根父级后自动调整阶段,javafx-2,javafx,Javafx 2,Javafx,当我点击按钮时,我需要在同一场景中显示一个面板,其中有一个额外的选项,但我不知道如何实现这种行为。将面板添加到rootVBox时,阶段未调整大小的问题 我已经编写了简单的代码来演示这个问题 import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.co

当我点击
按钮时,我需要在同一
场景中显示一个
面板
,其中有一个额外的选项
,但我不知道如何实现这种行为。将面板添加到root
VBox
时,
阶段
未调整大小的问题

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

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();
   }
}
导入javafx.application.application;
导入javafx.event.ActionEvent;
导入javafx.event.EventHandler;
导入javafx.scene.scene;
导入javafx.scene.control.Button;
导入javafx.scene.control.Label;
导入javafx.scene.layout.VBox;
导入javafx.stage.stage;
公共类主扩展应用程序{
公共静态void main(字符串[]args){
发射(args);
}
public void start(Stage)引发异常{
最终VBox根=新VBox();
按钮按钮=新按钮(“添加标签”);
root.getChildren().add(按钮);
setOnAction(新的EventHandler(){
公共无效句柄(ActionEvent事件){
root.getChildren().add(新标签(“hello”);
}
});
舞台场景(新场景(根));
stage.show();
}
}
我想我需要调用一些方法来通知根容器进行布局,但我尝试的所有方法都没有给我带来想要的结果。

程序正常运行

我认为,您的程序几乎按照您的预期工作(当您单击“添加标签”按钮时,一个新标签将添加到场景中)

为什么你看不到它工作

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

如何才能让它工作

添加标签后手动调整阶段窗口的大小

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

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

添加每个新标签后

只需更改代码

button.setOnAction(new EventHandler<ActionEvent>()
{
     public void handle(ActionEvent event)
     {
         root.getChildren().add(new Label("hello"));
         stage.sizeToScene();
     }
});
button.setOnAction(新的EventHandler()
{
公共无效句柄(ActionEvent事件)
{
root.getChildren().add(新标签(“hello”);
stage.sizeToScene();
}
});
button.setOnAction(new EventHandler<ActionEvent>()
{
     public void handle(ActionEvent event)
     {
         root.getChildren().add(new Label("hello"));
         stage.sizeToScene();
     }
});