JavaFX TreeView: setGraphic() for different levels

2019-08-06 13:24发布

问题:

I'm creating a TreeView that should have different graphics for different levels of the treestructure. It is a 3-level structure, where the root is hidden.

The graphic for expandable nodes: http://i.imgur.com/wv00CEi.png

The graphic for leaf nodes:

Just a label in an hBox.

This is what I have tried so far, but I get a nullPointerException basically saying getTreeView is null:

CustomTreeCellFactory

public final class CustomTreeCellFactory extends TreeCell<String>{
private TextField textField;
private HBox hBox;

public CustomTreeCellFactory(){
    super();
    if (getTreeView()==null){
        System.out.println("Her er problem");
    }
    if (getTreeView().getTreeItemLevel(getTreeItem())==1){
        try {
            hBox = (HBox) FXMLLoader.load(getClass().getResource("/Views/TreCell.fxml"));
        } catch (IOException e) {
            System.out.println("This didn't work");
            e.printStackTrace();
        }
    }
    else if (getTreeView().getTreeItemLevel(getTreeItem())==2){
        try {
            hBox = (HBox) FXMLLoader.load(getClass().getResource("/Views/TreCellLowestLevel.fxml"));
        } catch (IOException e) {
            System.out.println("This didn't work");
            e.printStackTrace();
        }
    }


}

Code snippet from where I set the Cell Factory

TreeView<String> tree = (TreeView) parent.getChildren().get(0);
    tree.setRoot(root);
    tree.setShowRoot(false);
    tree.setEditable(true);
    tree.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
        @Override
        public TreeCell<String> call(TreeView<String> param) {
            return new CustomTreeCellFactory();
        }
    });

回答1:

I found out what the problem was.

What I tried to do needed to be done in the update-method, when the TreeView is set.

Here's the code that solved the problem:

**Constructor**
public CustomTreeCellFactory(){
    try {
        hBox = (HBox) FXMLLoader.load(getClass().getResource("/Views/TreCell.fxml"));
    } catch (IOException e) {
        System.out.println("This didn't work");
        e.printStackTrace();
    }
    try {
        hBoxLeaf = (HBox) FXMLLoader.load(getClass().getResource("/Views/TreCellLowestLevel.fxml"));
    } catch (IOException e) {
        System.out.println("This didn't work");
        e.printStackTrace();
    }

}

Update Method

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

    if (item != null) {
        if (getTreeView().getTreeItemLevel(getTreeItem())==1) {
            setGraphic(this.hBox);
        }else if (getTreeView().getTreeItemLevel(getTreeItem())==2){
            setGraphic(this.hBoxLeaf);
        }
    } else {
        setGraphic(null);
    }
}