使用单元工厂自定义TreeCell

时间:2014-11-04 14:38:21

标签: javafx fxml

我试图像这样代表一个TreeCell:

http://i.imgur.com/wv00CEi.png

我试过阅读细胞工厂,我知道我必须使用这个功能。但是如何为所有TreeCells设置图形呢?图像作为HBox存储在.fxml文件中。

非常感谢你:)

P.S。不一定在这里寻找答案中的代码,更多关于如何做到这一点的一般解释或为什么它不起作用。

这是我尝试过的代码。 fxml文件与文件位于同一文件夹中。

这是我得到的错误代码:

线程“JavaFX Application Thread”中的异常java.lang.NullPointerException:位置是必需的。

    @Override
public void updateItem(String item, boolean empty) {
   super.updateItem(item, empty);
    try {
        this.hBox = (HBox) FXMLLoader.load(getClass().getResource("/Views/TreeCell.fxml"));
    } catch (IOException e) {
        System.out.println("This didn't work");
        e.printStackTrace();
    }
    if (item != null) {
        setGraphic(this.hBox);
    } else {
        setGraphic(null);
    }
}

1 个答案:

答案 0 :(得分:2)

您获得的例外意味着FXMLLoader无法找到您指定的FXML文件。如果FXML文件与当前类位于同一个包中,则应该能够使用

    this.hBox = (HBox) FXMLLoader.load(getClass().getResource("TreeCell.fxml"));

如果您使用前导/启动资源路径,它将被解释为相对于类路径。

使用您显示的代码,性能可能会非常差。使用单元工厂时,相对很少创建单元格,但可能会非常频繁地调用它们的updateItem(...)方法(特别是在快速滚动期间,或者在展开和折叠树节点时)。在该方法中阅读和解析FXML文件可能是一个坏主意。

相反,您可以在创建单元格时读取文件一次,然后只需在HBox方法中重复使用生成的updateItem()

tree.setCellFactory(treeView -> {
    HBox hbox ;
    try {
        hbox = (HBox) FXMLLoader.load(getClass().getResource("TreeCell.fxml"));
    } catch (Exception exc) {
        throw new RuntimeException(exc) ;
    }
    return new TreeCell<String>() {
        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            if (item == null) {
                setGraphic(null);
            } else {
                // configure graphic with cell data etc...
                setGraphic(hbox);
            }
        }
    };
});
相关问题