【问题标题】:Why does the method "getChildren" doesn't work with Pane?为什么“getChildren”方法不适用于 Pane?
【发布时间】:2015-08-30 11:44:13
【问题描述】:

我已经搜索了答案,但只发现了与 GridPane 相同的问题,并且解决方案(使用方法“getContent()”或“getTabs()”)对我不起作用,因为它也是不可能的窗格的方法。

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

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

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

    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.setResizable(false);
    stage.show();
}

非常感谢您的帮助:)

【问题讨论】:

    标签: javafx-8


    【解决方案1】:

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

    AnchorPane root = FXMLLoader.<AnchorPane>load(getClass().getResource("Lost.fxml"));
    

    你的实际问题:

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

    因为在行

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

    .getChildrenUnmodifiable() 将返回 ObservableList&lt;Node&gt; 并且
    .get(0) 将在此列表的索引 0 处返回 Node,并且 Node 是所有节点(窗格、控件等)的顶级基类,没有 .getChildren() 方法。

    如果您确定子列表的 index=0 处有一个Pane,则可以对其进行强制转换:

     ObservableList<Node> paneChildren = ( (Pane) root.getChildren().get(0) ).getChildren();
     paneChildren.add( new Button("Do it!") );
    

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

    【讨论】:

    • 我的意思是 get(0) 之后的 getChildren() 方法。我不能在我的根目录上使用 getChildren() 方法,因为它说“它在 Parent 中具有受保护的访问权限”并且我想将 Button 添加到变量根目录(这是我的 AnchorPane)中,而不是添加到我的窗格中。所以我不能在窗格上使用它,因为我使用 getChildrenUmodifiable 方法获取对象窗格?比如何在我的 Parent 对象上使用 getChildren ? PS:谢谢你的帮助,希望你能理解我的“进一步的问题” :)
    猜你喜欢
    • 1970-01-01
    • 2020-09-25
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多