Swing/InsertSiblingNode のバックアップ差分(No.3)
- バックアップ一覧
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- バックアップ を表示
- Swing/InsertSiblingNode へ行く。
- 1 (2016-07-04 (月) 01:00:33)
- 2 (2017-09-26 (火) 11:02:08)
- 3 (2019-03-22 (金) 19:02:21)
- 4 (2020-12-31 (木) 00:25:36)
- 5 (2023-06-29 (木) 15:34:35)
- 追加された行はこの色です。
- 削除された行はこの色です。
---
category: swing
folder: InsertSiblingNode
title: JTreeの選択されたノードの前後に新規ノードを挿入する
tags: [JTree, JPopupMenu, DefaultMutableTreeNode, TreeNode, TreeModel]
author: aterai
pubdate: 2016-07-04T00:56:54+09:00
description: JTreeのノードを選択してポップアップメニューを開き、その前または後ろに新規ノードを挿入します。
image: https://lh3.googleusercontent.com/-P_GnYongQ64/V3kweryY25I/AAAAAAAAOdI/CqWS6tum8402qaWo1130iBF5r1tVPkJCwCCo/s800/InsertSiblingNode.png
---
* 概要 [#summary]
`JTree`のノードを選択してポップアップメニューを開き、その前または後ろに新規ノードを挿入します。
#download(https://lh3.googleusercontent.com/-P_GnYongQ64/V3kweryY25I/AAAAAAAAOdI/CqWS6tum8402qaWo1130iBF5r1tVPkJCwCCo/s800/InsertSiblingNode.png)
* サンプルコード [#sourcecode]
#code(link){{
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();
MutableTreeNode child = new DefaultMutableTreeNode("New preceding sibling");
int index = model.getIndexOfChild(parent, self);
parent.insert(child, index);
model.reload(parent);
//or: model.insertNodeInto(child, parent, index);
}
};
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();
MutableTreeNode child = new DefaultMutableTreeNode("New following sibling");
int index = model.getIndexOfChild(parent, self);
parent.insert(child, index + 1);
model.reload(parent);
//or: model.insertNodeInto(child, parent, index + 1);
}
};
}}
* 解説 [#explanation]
- `add child node`
-- 選択されたノードの子ノードとして新規ノードを追加
-- [[JTreeのノード追加、削除>Swing/AddNode]]
- `insert preceding sibling node`
-- 選択されたノードの兄ノードとして新規ノードを追加
- `insert following sibling node`
-- 選択されたノードの弟ノードとして新規ノードを追加
* 参考リンク [#reference]
- [[JTreeのノード追加、削除>Swing/AddNode]]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/tree/MutableTreeNode.html#insert-javax.swing.tree.MutableTreeNode-int- MutableTreeNode#insert(...) (Java Platform SE 8)]
* コメント [#comment]
#comment
#comment