JavaFX TreeItem字符串未出现

时间:2014-02-22 01:24:49

标签: treeview javafx

经过几个小时的尝试后,我终于有点设法弄清楚如何在TreeView中将监听器挂钩到TreeItems,它可能根本不是正确的方法,但是到目前为止它是有效的。 虽然有一点不是,那就是“标签”或更好的说,TreeItems中的文字不再出现了。 enter image description here

任何人都可以查看我的代码并告诉我,如果我要么完全错误,要么为什么文本不再显示? 提前谢谢。

代码:

TreeView<String> tree = new TreeView<>(); 

TreeItem<String> treeRoot = new TreeItem<>(Login.name + " - " + Login.accountType);
treeRoot.getChildren().addAll(new TreeItem<>("Branches"),
        new TreeItem<>("Planning"), new TreeItem<>("Courses"),
        new TreeItem<>("Add new item"));

treeRoot.getChildren().get(1).getChildren().addAll(
        new TreeItem<>("2014 - Q1"), new TreeItem<>("2014 - Q2"),
        new TreeItem<>("2014 - Q3"), new TreeItem<>("2014 - Q4"));
treeRoot.getChildren().get(3).getChildren().addAll(
        new TreeItem<>("Branch"), new TreeItem<>("Course"));

for(String str : loadBranchData()) {
    treeRoot.getChildren().get(0).getChildren().add(
        new TreeItem<>(str));
}
for(String str : loadCourseData()) {
    treeRoot.getChildren().get(2).getChildren().add(
        new TreeItem<>(str));
}
for(int c = 0; c <= 2; c++) {
    treeRoot.getChildren().get(c).setExpanded(true);
}

treeRoot.setExpanded(true);
tree.setPrefWidth(PREFWIDTH);
tree.setRoot(treeRoot);
tree.setShowRoot(true);
tree.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){
    @Override
    public TreeCell<String> call(TreeView<String> p) {
        return new EpicTreeCell();
    }
});
...
    private final class EpicTreeCell extends TreeCell<String> {
        @SuppressWarnings("unchecked")
        super.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent evt) {
                System.out.println("TEST?");
            }
        });       
    }

1 个答案:

答案 0 :(得分:4)

定义自定义单元格后,应在其重写的setText()方法中调用updateItem()方法。

private final class EpicTreeCell extends TreeCell<String> {

    public EpicTreeCell() {
        setOnMouseClicked (
                new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent evt) {
                        System.out.println("TEST?");
                    }
                }
        );
    }

    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setText(null);
        } else {
            setText(getItem() == null ? "" : getItem().toString());
        }
        setGraphic(null);
    }
}

有关详细信息,请参阅"Custom Java-fx cellfactory messes up the setCellValueFactory"