问题
I have a JTree with editable nodes.
How can I programmatically trigger the tree cell edit event, i.e. bring up the node-renaming textbox in place of a highlighted node, as if the user manually highlighted it and pressed F2?
Basically I want to add a "Rename" menu item or toolbar button, to clue users in on that particular function of the tree, and I want it to function identically to an F2 keypress when the user highlights a node.
回答1:
1) some node is selected (by Mouse
/ KeyBoard
event) and by listening by TreeSelectionListener
, then selected path has unique ID
2) add Swing Action
to JMenuItem
(in JPopup
???, not clear from your question, how to get node from /to ???)
3) create class, void, whatever and to fire
SwingUtilities.invokeLater(new Runnable() {
public void run() {
tree.startEditingAtPath(path);
}
});
4) based on answer by @Michael Dunn to my question on another forum
回答2:
See this tutorial
To make the text in the tree's nodes editable, we invoke setEditable(true) on the tree. When the user has finished editing a node, the model generates a tree model event that tells any listeners — including the JTree — that tree nodes have changed. Note that although DefaultMutableTreeNode has methods for changing a node's content, changes should go through the DefaultTreeModel cover methods. Otherwise, the tree model events would not be generated, and listeners such as the tree would not know about the updates.
EDIT:
To add a context menu for a node, see this question: Right-click context menu for Java JTree?.
来源:https://stackoverflow.com/questions/14184995/swing-triggering-tree-cell-edit-event