Swing/InsertSiblingNode のバックアップ(No.1)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/InsertSiblingNode へ行く。
- title: JTreeの選択されたノードの前後に新規ノードを挿入する tags: [JTree, JPopupMenu, DefaultMutableTreeNode, TreeNode, TreeModel] author: aterai pubdate: 2016-07-04T00:56:54+09:00 description: JTreeのノードを選択してポップアップメニューを開き、その前または後ろに新規ノードを挿入します。
概要
JTree
のノードを選択してポップアップメニューを開き、その前または後ろに新規ノードを挿入します。
Screenshot

Advertisement
サンプルコード
Action addAboveAction = new AbstractAction("insert preceding sibling node") {
@Override public void actionPerformed(ActionEvent e) {
JTree tree = (JTree) getInvoker();
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
MutableTreeNode self = (MutableTreeNode) path.getLastPathComponent();
MutableTreeNode parent = (MutableTreeNode) self.getParent();
int index = model.getIndexOfChild(parent, self);
DefaultMutableTreeNode child = new DefaultMutableTreeNode("New preceding sibling");
parent.insert(child, index);
model.reload(parent);
scrollAndSelect(tree, child);
}
};
Action addBelowAction = new AbstractAction("insert following sibling node") {
@Override public void actionPerformed(ActionEvent e) {
JTree tree = (JTree) getInvoker();
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
MutableTreeNode self = (MutableTreeNode) path.getLastPathComponent();
MutableTreeNode parent = (MutableTreeNode) self.getParent();
int index = model.getIndexOfChild(parent, self);
DefaultMutableTreeNode child = new DefaultMutableTreeNode("New following sibling");
parent.insert(child, index + 1);
model.reload(parent);
scrollAndSelect(tree, child);
}
};
View in GitHub: Java, Kotlin解説
add child node
- 選択されたノードの子ノードとして新規ノードを追加
- JTreeのノード追加、削除
insert preceding sibling node
- 選択されたノードの兄ノードとして新規ノードを追加
insert following sibling node
- 選択されたノードの弟ノードとして新規ノードを追加