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

时间:2013-10-29 22:26:56

标签: javafx-2 javafx

当我点击Panel时,我需要在同一个Scene中显示一个Button额外选项,但我不知道如何实现此行为。将面板添加到根StageVBox未调整大小的问题。

我编写了简单的代码来演示问题。

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

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

2 个答案:

答案 0 :(得分:27)

计划作品

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

为什么你看不到它的工作

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

如何使其发挥作用

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

OR

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

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

OR

添加每个新标签后,size the stage to the scene

stage.sizeToScene();

答案 1 :(得分:0)

只需更改代码

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