如何在JavaFX中将场景添加到堆栈窗格中

问题描述 投票:1回答:2

我想在堆栈窗格中创建一个场景,所以我只用了代码

StackPane vb = new StackPane();
Scene scene  = new Scene(vb);
vb.getParent().add(scene);

但是显示类似The method add(Scene) is undefined for the type Parent的错误。

有人可以建议我在堆栈窗格中添加场景的想法吗?

javafx-8
2个回答
1
投票

类型为Parent的方法add(Scene)未定义。

Parent中没有带有任何参数的add方法。不确定您的意思。

从Scene类的Javadoc:

JavaFX Scene类是场景中所有内容的容器图。

场景不会扩展Node,因此您无法添加到其他Node。它打算成为舞台的轻量化部分。

对于分页:您可以:

  • 更改舞台场景
  • 更改场景的根节点
  • 更改窗格的内容(例如BorderPane的中心)

我想第三个选项最适合分页,因为您可能希望在分页时保留页眉(菜单,工具栏,...)和页脚(状态栏,...)。


0
投票

我发现的更好的解决方案:将您的根添加到StackPane,然后将其添加到场景。

[就像自己一样,我试图在彼此之间添加多个场景。您正在执行的操作的问题是Scene无法添加到任何内容。

所以改为:

    // Create your StackPane to put everything in
    StackPane stackPane = new StackPane();

    // Create your content
    // ... Ellipse
    Ellipse ellipse = new Ellipse(110, 70);
    ellipse.setFill(Color.LIGHTBLUE);

    // ... Text
    Text text = new Text("My Shapes");
    text.setFont(new Font("Arial Bold", 24));

    // ... GridPane
    Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));

然后将它们全部一起添加到StackPane中,并将StackPane添加到场景中。

    // add all
    // now all my content appears on top of each other in my stackPane
    // Note: The order they stack is root -> ellipse -> text
    stackPane.getChildren().addAll(root, ellipse, text); 

    // make your Scene
    Scene scene = new Scene(stackPane, 300, 275, Color.BLACK);

    // finalize your stage
    primaryStage.setScene(scene);
    primaryStage.show();
© www.soinside.com 2019 - 2024. All rights reserved.