首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么"getChildren“方法不适用于Pane?

为什么"getChildren“方法不适用于Pane?
EN

Stack Overflow用户
提问于 2015-08-30 11:44:13
回答 1查看 7.2K关注 0票数 1

我已经搜索了答案,但只在GridPane和解决方案(使用"getContent()“或"getTabs()")对我不起作用,因为对于Pane也没有可能的方法。

我想要做的是向窗格元素添加一个Button。我搜索解决方案,它们总是使用getchildren().add(Node e)方法。

这是我的代码,我检查了我的对象的类是否是Pane,是的,System.out显示它是Pane。

代码语言:javascript
复制
@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("Lost.fxml"));

    Screen screen = Screen.getPrimary();
    Rectangle2D bounds = screen.getVisualBounds();
    stage.setX(bounds.getMinX());
    stage.setY(bounds.getMinY());
    stage.setWidth(bounds.getWidth());
    stage.setHeight(bounds.getHeight());

    Button startButton = new Button("Start1");
    //Einfügen des Eventhandlers des Buttons
    startButton.setOnAction(null);
    //Bestimmen der Position des Buttons
    startButton.setPrefHeight((stage.getHeight()/2));
    startButton.setPrefWidth((stage.getWidth()/2));

    System.out.println(root.getChildrenUnmodifiable().get(0).getClass());

root.getChildrenUnmodifiable().get(0).getChildren();

代码语言:javascript
复制
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.setResizable(false);
    stage.show();
}

我真的很感谢你的帮助

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-30 11:58:58

如果"Lost.fxml“中的顶部布局是AnchorPane,则可以在加载时直接指定它:

代码语言:javascript
复制
AnchorPane root = FXMLLoader.<AnchorPane>load(getClass().getResource("Lost.fxml"));

你的实际问题:

为什么“getChildren”方法不适用于Pane?

因为在队伍里

代码语言:javascript
复制
root.getChildrenUnmodifiable().get(0).getChildren();

.getChildrenUnmodifiable()将返回ObservableList<Node>

.get(0)将在该列表的索引0处返回一个Node,并且Node是所有节点(窗格、控件等)的顶级基类,它没有.getChildren()方法。

如果您确信在index=0 of子列表中有一个Pane,则可以对其进行强制转换:

代码语言:javascript
复制
 ObservableList<Node> paneChildren = ( (Pane) root.getChildren().get(0) ).getChildren();
 paneChildren.add( new Button("Do it!") );

我使用的是root.getChildren()而不是root.getChildrenUnmodifiable(),因为我们现在的顶部是AnchorPane root

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32296187

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档