Swing/ToggleTreeNodeByKeyStroke のバックアップ差分(No.3)
- バックアップ一覧
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- バックアップ を表示
- Swing/ToggleTreeNodeByKeyStroke へ行く。
- 1 (2023-12-04 (月) 00:01:47)
- 2 (2023-12-30 (土) 23:09:37)
- 3 (2024-06-30 (日) 02:39:57)
- 追加された行はこの色です。
- 削除された行はこの色です。
---
category: swing
folder: ToggleTreeNodeByKeyStroke
title: JTreeのノード展開・折り畳み状態をキー入力で切り替える
tags: [JTree, TreeNode]
author: aterai
pubdate: 2023-12-04T00:00:25+09:00
description: JTreeの親ノードが選択されている場合、キー入力でその展開・折り畳み状態を切り替えます。
image: https://drive.google.com/uc?id=13FbBMCLGuFg240-BFwNXCWSCryo813Dl
---
* 概要 [#summary]
`JTree`の親ノードが選択されている場合、キー入力でその展開・折り畳み状態を切り替えます。
#download(https://drive.google.com/uc?id=13FbBMCLGuFg240-BFwNXCWSCryo813Dl)
* サンプルコード [#sourcecode]
#code(link){{
InputMap im = tree.getInputMap(JComponent.WHEN_FOCUSED);
int modifiers1 = InputEvent.CTRL_DOWN_MASK;
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_T, modifiers1), "toggle");
int modifiers2 = InputEvent.CTRL_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK;
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_T, modifiers2), "toggle2");
ActionMap am = tree.getActionMap();
am.put("toggle2", new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
int row = tree.getLeadSelectionRow();
TreePath path = tree.getPathForRow(row);
if (!tree.isExpanded(path)) {
tree.expandPath(path);
} else {
tree.collapsePath(path);
}
}
});
}}
* 解説 [#explanation]
- `BasicTreeUI.TreeToggleAction`
-- `BasicTreeUI`に`TreeToggleAction`が実装されてすでに`JTree`の`ActionMap`に追加されているので、これを呼び出す`KeyStroke`を`JTree`の`InputMap`に追加
-- このサンプルではKBD{Ctrl+T}で`TreeToggleAction`を実行
-- 展開`+`、折り畳み`-`アイコンのシングルクリックと同等
-- `TreeNode`の左マウスボタンでのダブルクリック(`JTree#getToggleClickCount()`がデフォルトの`2`の場合)とは異なり、`TreeToggleAction`によるノードトグルはその子ノード以外の選択状態は維持される
- `JTree#isExpanded(...), JTree#collapsePath(...)`
-- `JTree#isExpanded(TreePath)`で展開・折り畳み状態をチェックし、`JTree#isExpanded(...)`で展開、`JTree#collapsePath(...)`で折り畳みを実行する`AbstractAction`を`JTree`の`ActionMap`に追加
-- このサンプルではKBD{Shift+Ctrl+T}でこの`Action`を実行
-- `TreeToggleAction`とは異なり、行表示スクロールなどの処理を省略している
* 参考リンク [#reference]
- [[JTreeで特定のノードをマウスクリックした場合のみ展開不可に設定する>Swing/PreventToggleClickNodeExpanding]]
- [https://bugs.openjdk.org/browse/JDK-8317771 [JDK-8317771] [macos14] Expand/collapse a JTree using keyboard freezes the application in macOS 14 Sonoma - Java Bug System]
* コメント [#comment]
#comment
#comment