JavaFX:将子项添加到root父项后自动调整阶段 [英] JavaFX: autoresize stage after adding child to root parent

查看:889
本文介绍了JavaFX:将子项添加到root父项后自动调整阶段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

推荐答案

程序作品

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

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).

为什么看不到它

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

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.

如何使其工作

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

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

添加每个新的标签,调整舞台大小

stage.sizeToScene();

这篇关于JavaFX:将子项添加到root父项后自动调整阶段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆