在我的JavaFX App中,我想通过点击Menu上的按钮来运行TreeView CellFactory中实现的startEdit()方法。问题是,我无法直接通过Callback获取TreeItem的方法,而且我没有看到任何其他方法来使每个TreeItem可编辑。
这是来自我的Tree实现的代码,cellfactory来自oracle教程
private class WTree extends TreeView<String> {
private TreeItem<String> rootItem;
private TreeItem<String> sItem;
private TreeItem<String> aItem;
private TreeItem<String> iItem;
private TreeItem<String> uItem;
public WTree() {
super();
rootItem = new TreeItem<String>("Employees");
sItem = new TreeItem<String>("Sales Departament");
aItem = new TreeItem<String>("Accounts Departament");
iItem = new TreeItem<String>("IT Support");
uItem = new TreeItem<String>("Undercover");
this.setRoot(rootItem);
rootItem.getChildren().addAll(sItem, aItem, iItem, uItem);
rootItem.setExpanded(true);
this.setEditable(true);
this.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){
@Override
public TreeCell<String> call(TreeView<String> p) {
return new TextFieldTreeCellImpl();
}
});
}
}
private final class TextFieldTreeCellImpl extends TreeCell<String> {
private TextField textField;
private boolean focused;
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();
}
}
private class WTextField extends TextField {
public WTextField(String desc) {
super();
this.setPromptText(desc);
this.setPrefWidth(100);
}
}
我的菜单来自menuitem
editLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
if(tree.isFocused()) {
tree.requestFocus();
FocusModel<TreeItem<String>> treeSelect = tree.getFocusModel();
TreeItem<String> foc = treeSelect.getFocusedItem();
}
答案 0 :(得分:0)
我不确定我是否真的完全理解你的问题,但我认为你正在寻找TreeView.edit(...)
方法。你可以做点什么
editLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
tree.edit(tree.getSelectionModel().getSelectedItem());
}
});