当有人双击它时,我正在使用以下代码使树视图中的某些treeItem可编辑。最近我更改了TreeView,因此填充了TreeItem<MyNode>
而不是TreeItem<String>
。可编辑单元格的代码现在不起作用,我不知道应该对它进行哪些更改:
TextFieldTreeCellImpl.java:
public final class TextFieldTreeCellImpl extends TreeCell<String> {
private TextField textField;
String oldItem="";
private Connection connection;
String url = "jdbc:sqlserver://localhost:1433;databaseName=HOGENT1415_11";
String user = "sa";
String password = "root";
Statement statement;
public TextFieldTreeCellImpl(){
}
@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());
}
}
}
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();
}
}
这是完成魔术的代码:
selectionTreeView.setEditable(true);
selectionTreeView.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){
@Override
public TreeCell<String> call(TreeView<String> p) {
TextFieldTreeCellImpl textField = null;
textField = new TextFieldTreeCellImpl();
return textField;
}
});
非常感谢帮助。
答案 0 :(得分:0)
James_D所说的通常会奏效。
所以将所有TreeCell更改为TreeCell。
还要注意这一行:
commitEdit(textField.getText());
这应该成为:
commitEdit(new MyNode(*parameters*));
我不知道你对MyNode有什么参数,但是例如如果你有一个int类型的参数,你还需要为此编写一个额外的私有方法(比如getString方法):
private String getItemInt() {
return getItem() == null ? "" : getItem().giveItemInt();
}