【问题标题】:Dynamically accessing/traversing/manipulating JavaFX nodes created from FXML outside the controller class动态访问/遍历/操作从控制器类外部的 FXML 创建的 JavaFX 节点
【发布时间】:2013-01-23 06:33:28
【问题描述】:

谁能帮帮我。我是 JavaFX 和 FXML 的新手,我已经尝试了无数小时试图做一些没有任何运气的事情。 有人可以给我看一个代码的工作示例

1) 加载包含节点(例如标签和按钮)的 FXML,这些节点在不同的窗格和节点中嵌套了几层;

2) 遍历列出节点的整个场景(例如标签和按钮);

3) 将 Java 代码耦合到一个节点(例如标签和按钮),以便我可以在为 FXML 定义的控制器类之外更改其属性(例如它的标签和内容)。

我的目标是使用 Scene Builder 构建 UI,然后能够动态更改场景的内容以及向其中添加其他节点。我的问题是我无法到达场景/舞台中的对象。

这是我一直在使用的代码。 cmets表明我是什么 正在寻找。

//

public void start(Stage stage) throws Exception {
    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Sample.fxml"));
    Parent root = (Parent)fxmlLoader.load();
    SampleController controller = (SampleController)fxmlLoader.getController();
    controller.label.setText("Label text has been set");
    controller.button.setText("Button text has been set");

    // Looking for an example of traversing all the objects within the controller
    // looking for an object such as a TableView and its columns. Would like to
    // attach code outside the controller which populates the TableView.

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

【问题讨论】:

  • 发布一个 FXML 示例以及您想要的输出。

标签: javafx fxml


【解决方案1】:

你必须递归获取root容器内的所有节点:

public void start(Stage stage) throws Exception {
   FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Sample.fxml"));
   Parent root = (Parent)fxmlLoader.load();

   List<Node> allNodes = getAllNodes(root);
   for(Node node : allNodes) {
      // do some stuff…
   }
   …
}

private List<Node> getAllNodes(Parent container) {
    List<Node> nodes = new ArrayList<Node>();
    for(Node node : container.getChildrenUnmodifiable())
    {
       nodes.add(node);
       if (node instanceof Parent) {
          Parent subContainer = (Parent) node;
          nodes.addAll( getAllNodes(subContainer) );
       }
    }
    return nodes;
}

您可以像以前一样访问控制器的@FXML 字段(例如 TableView)... :-)

另外,TableView 中有一个方法可以获取列,例如controller.tableView.getColumns()…

只需在全局范围内保存一个控制器实例,即可从任何地方访问它。

干杯

【讨论】:

    猜你喜欢
    • 2018-07-26
    • 1970-01-01
    • 2013-07-22
    • 2012-12-15
    • 2023-03-19
    • 2016-05-04
    • 1970-01-01
    • 2017-12-11
    • 2017-12-02
    相关资源
    最近更新 更多