我正在创建一个TreeView,它应该为不同级别的树结构提供不同的图形。它是一个三层结构,根隐藏在那里。
可展开节点的图形:https://i.stack.imgur.com/JVdxQ.png
叶节点的图形:
只是hBox中的一个标签。
到目前为止,我已经尝试过了,但我得到了一个nullPointerException,基本上是说getTreeView为null:
自定义TreeCellFactory
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();
}
}
}
设置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();
}
});
我发现了问题所在。
当设置TreeView时,我尝试做的事情需要在update方法中完成。
以下是解决问题的代码:
**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();
}
}
更新方法
@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);
}
}