JavaFX:CellFactory / Cells与单个节点

时间:2014-01-24 15:01:36

标签: java javafx

我对JavaFX中的TreeView有疑问。我不太明白使用cellfactory。

假设我有以下树:

public void initialize(TreeView<String> treeView){
    treeView.setRoot(new TreeItem<String>("Root"));
    root.getChildren().add(new TreeItem<String>("1"));
    root.getChildren().add(new TreeItem<String>("2"));
    root.getChildren().add(new TreeItem<String>("3"));
    root.getChildren().add(new TreeItem<String>("4"));
}

我想为每个项目添加一个Contextmenu。我做了以下事情:

treeView.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
     @Override
     public TreeCell<String> call(TreeView<String> stringTreeView) {
             return new ContextMenuCell();
        }
    });

ContextMenuCell.java如下所示:

public class ContextMenuCell extends TreeCell<String> {

    public ContextMenuCell (){
        setContextMenu(new ContextMenu(new MenuItem("Test")));
    }
}

这将为每个单元格添加一个上下文菜单,但Treeitems的标签会消失。如何让他们留下来或读书?

1 个答案:

答案 0 :(得分:2)

您需要覆盖TreeCell的updateItem方法,即绘制它的位置

private static final class ContextMenuCell extends TreeCell {

    ContextMenuCell() {
        setContextMenu(new ContextMenu(new MenuItem("Test")));
    }

    @Override
    public void updateItem(Object item, boolean empty) {
        super.updateItem(item, empty);
        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            setText(item.toString());
            setGraphic(getTreeItem().getGraphic());
        }
    }
}