• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTreeの選択状態を解除する
#navi(../)
RIGHT:Posted by [[terai]] at 2010-12-06
*JTreeの選択状態を解除する [#kdaff136]
JTreeでノード以外の領域をマウスでクリックした場合、選択状態を解除します。
---
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`でノード以外の領域をマウスでクリックした場合、選択状態を解除します。

-&jnlp;
-&jar;
-&zip;
#download(https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTWDzni-uI/AAAAAAAAAoo/r6UW4JENwgI/s800/TreeClearSelection.png)

//#screenshot
http://lh6.ggpht.com/_9Z4BYR88imo/TQTWDzni-uI/AAAAAAAAAoo/r6UW4JENwgI/s800/TreeClearSelection.png

**サンプルコード [#v9dc8a42]
#code{{
* サンプルコード [#sourcecode]
#code(link){{
tree.addMouseListener(new MouseAdapter() {
  public void mousePressed(MouseEvent e) {
    JTree tree = (JTree)e.getSource();
    if(tree.getRowForLocation(e.getX(), e.getY())<0) {
  @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();
    // }
  }
});
}}

**解説 [#x8c210f4]
上記のサンプルでは、JTree#getRowForLocation(...)メソッドを使用して、JTreeのノード以外のポイントがクリックされたかどうかを判断しています。ノードの選択解除自体は、JTree#clearSelection()が使用できます。
* 解説 [#explanation]
上記のサンプルでは、`JTree#getRowForLocation(...)`メソッドを使用して`JTree`のノード以外の場所がクリックされたかどうかを判断しています。ノードの選択解除自体は`JTree#clearSelection()`メソッドを使用しています。

**参考リンク [#u6021f39]
-[http://java.sun.com/javase/ja/6/docs/ja/api/javax/swing/JTree.html JTree (Java Platform SE 6)]のサンプルコード
- [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`を返す

**コメント [#n98afd93]
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTree.html JTree (Java Platform SE 8)]のサンプルコード

* コメント [#comment]
#comment
#comment