Swing/TreeClearSelection のバックアップソース(No.12)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- バックアップ を表示
- Swing/TreeClearSelection へ行く。
- 1 (2010-12-06 (月) 14:44:47)
- 2 (2010-12-06 (月) 18:11:37)
- 3 (2010-12-17 (金) 21:19:12)
- 4 (2010-12-18 (土) 02:55:07)
- 5 (2012-12-25 (火) 11:25:26)
- 6 (2013-10-11 (金) 12:53:36)
- 7 (2015-02-05 (木) 14:41:21)
- 8 (2016-09-10 (土) 23:43:03)
- 9 (2017-10-25 (水) 15:44:05)
- 10 (2019-04-01 (月) 18:17:21)
- 11 (2019-10-28 (月) 20:49:57)
- 12 (2021-05-22 (土) 04:40:38)
--- category: swing folder: TreeClearSelection title: JTreeの選択状態を解除する tags: [JTree, MouseListener] author: aterai pubdate: 2010-12-06T14:44:47+09:00 description: JTreeでノード以外の領域をマウスでクリックした場合、選択状態を解除します。 image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTWDzni-uI/AAAAAAAAAoo/r6UW4JENwgI/s800/TreeClearSelection.png --- * 概要 [#summary] `JTree`でノード以外の領域をマウスでクリックした場合、選択状態を解除します。 #download(https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTWDzni-uI/AAAAAAAAAoo/r6UW4JENwgI/s800/TreeClearSelection.png) * サンプルコード [#sourcecode] #code(link){{ tree.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { JTree tree = (JTree) e.getComponent(); if (tree.getRowForLocation(e.getX(), e.getY()) < 0) { tree.clearSelection(); } // or: // if (tree.getPathForLocation(e.getX(), e.getY()) == null) { // tree.clearSelection(); // } } }); }} * 解説 [#explanation] 上記のサンプルでは、`JTree#getRowForLocation(...)`メソッドを使用して`JTree`のノード以外の場所がクリックされたかどうかを判断しています。ノードの選択解除自体は`JTree#clearSelection()`メソッドを使用しています。 - [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTree.html#getRowForLocation-int-int- JTree#getRowForLocation(...) (Java Platform SE 8)] -- 指定された位置に対応する行を返す -- 指定された位置が表示セルの境界外にある場合は`-1` - [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTree.html#getPathForLocation-int-int- JTree#getPathForLocation(...) (Java Platform SE 8)] -- 指定された位置にあるノードの`TreePath`を返す -- 指定された位置が表示セルの境界外にある場合は`null`を返す * 参考リンク [#reference] - [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTree.html JTree (Java Platform SE 8)]のサンプルコード * コメント [#comment] #comment #comment