【问题标题】:JavaFX: autoresize stage after adding child to root parentJavaFX:将子级添加到根父级后自动调整大小阶段
【发布时间】:2013-10-29 22:26:55
【问题描述】:

当我单击Button 时,我需要在相同的Scene 中显示带有额外选项的Panel,但我不知道如何实现此行为。当我将面板添加到根VBox 时,Stage 没有调整大小的问题。

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

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-2 javafx


    【解决方案1】:

    节目作品

    您的程序几乎按照我的预期运行(当您单击“添加标签”按钮时,场景中会添加一个新标签)。

    为什么你看不到它工作

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

    怎样做才能看到它的工作

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

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

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

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

    stage.sizeToScene();
    

    【讨论】:

      【解决方案2】:

      只需更改代码

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-29
        • 2015-07-21
        • 1970-01-01
        • 2014-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-09
        相关资源
        最近更新 更多