我正在创建一个TreeView,它应该为不同级别的树结构提供不同的图形。它是一个三层结构,隐藏了根。
可扩展节点的图形: http://i.imgur.com/wv00CEi.png
叶子节点的图形:
只是hBox中的标签。
这是我到目前为止所尝试过的,但是我得到一个nullPointerException,基本上说getTreeView为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();
}
}
}
我设置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();
}
});
答案 0 :(得分:1)
我发现了问题所在。
设置TreeView时,我需要在update-method中完成所需的操作。
这是解决问题的代码:
**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);
}
}