我是JavaFx的新手。在树视图中,如果我添加一个stringItem的字符串(TreeItem<String>
),我们就可以使用以下代码编辑,添加或删除节点。
treeView.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){
@Override
public TreeCell<String> call(TreeView<String> p) {
return new TextFieldTreeCellImpl(treeView);
}
});
但是如果treeItems可以是任何类型(TreeItem<?>
),我们可以获取树但无法查看,无法添加或删除节点。它抛出了类型转换错误。请分享你的建议。我的代码如下,
在这里
public TreeItem<?> root;
TreeView<String> treeView = new TreeView<String>((TreeItem<String>) tree.root);
treeView.setEditable(true);
treeView.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){
@Override
public TreeCell<String> call(TreeView<String> p) {
return new TextFieldTreeCellImpl(treeView);
}
});
box.getChildren().add(treeView);
stage.setScene(scene);
stage.show();
}
private final class TextFieldTreeCellImpl extends TreeCell<String> {
private TextField textField;
private ContextMenu addMenu = new ContextMenu();
public TextFieldTreeCellImpl(TreeView<String> p) {
MenuItem addMenuItem = new MenuItem("Add Nodes");
MenuItem deleteMenuItem = new MenuItem("Delete Nodes");
addMenu.getItems().add(addMenuItem);
addMenu.getItems().add(deleteMenuItem);
addMenuItem.setOnAction(new EventHandler() {
public void handle(Event t) {
TreeItem newNodes = p.getSelectionModel().getSelectedItem();
boolean remove = newNodes.getParent().getChildren().add(newNodes);
}
});
deleteMenuItem.setOnAction(new EventHandler() {
public void handle(Event t) {
TreeItem removeNodes = p.getSelectionModel().getSelectedItem();
boolean remove = removeNodes.getParent().getChildren().remove(removeNodes);
System.out.println("Remove");
}
});
}
@Override
public void startEdit() {
super.startEdit();
if (textField == null) {
createTextField();
}
setText(null);
setGraphic(textField);
textField.selectAll();
}
@Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(getTreeItem().getGraphic());
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
// }
// setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(getTreeItem().getGraphic());
if (
!getTreeItem().isLeaf()&&getTreeItem().getParent()!= null
){
setContextMenu(addMenu);
}
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(textField.getText());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}