TITLE:JTreeの行選択し、背景色を変更
#navi(../)
RIGHT:Posted by [[aterai]] at 2011-01-17
*JTreeの行選択し、背景色を変更 [#r6a7991f]
JTreeの行をクリックして選択し、行全体を選択色で描画します。

-&jnlp;
-&jar;
-&zip;

//#screenshot
#ref(http://lh6.ggpht.com/_9Z4BYR88imo/TTPdCvaUyfI/AAAAAAAAAyQ/QnF4vHjyUiM/s800/TreeRowSelection.png)

**サンプルコード [#adcacb20]
#code{{
final Color SELC = new Color(100,150,200);
JTree tree = new JTree() {
  @Override public void paintComponent(Graphics g) {
    g.setColor(getBackground());
    g.fillRect(0,0,getWidth(),getHeight());
    if(getSelectionCount()>0) {
      for(int i: getSelectionRows()) {
        Rectangle r = getRowBounds(i);
        g.setColor(SELC);
        g.fillRect(0, r.y, getWidth(), r.height);
      }
    }
    super.paintComponent(g);
    if(getLeadSelectionPath()!=null) {
      Rectangle r = getRowBounds(getRowForPath(getLeadSelectionPath()));
      g.setColor(SELC.darker());
      g.drawRect(0, r.y, getWidth()-1, r.height-1);
    }
  }
};
tree.setUI(new javax.swing.plaf.basic.BasicTreeUI() {
  @Override public Rectangle getPathBounds(JTree tree, TreePath path) {
    if(tree != null && treeState != null) {
      return getPathBounds(path, tree.getInsets(), new Rectangle());
    }
    return null;
  }
  private Rectangle getPathBounds(TreePath path, Insets insets, Rectangle bounds) {
    bounds = treeState.getBounds(path, bounds);
    if(bounds != null) {
      bounds.width = tree.getWidth();
      bounds.y += insets.top;
    }
    return bounds;
  }
});
tree.setOpaque(false);
}}

**解説 [#r208490e]
以下のような設定で、JTreeを行選択できるように変更し、表示もNimbus Look&Feel風に描画するようにしています。

- BasicTreeUI#getPathBounds(...)をオーバーライドして、ノードではなく、行のクリックで選択可能に変更
- JTreeをsetOpaque(false)で透明にし、JTree#paintComponent(...)をオーバーライドして選択された行を背景色で描画
- 不透明にしたTreeCellRendererを使用して、ノードの選択色をJTree#paintComponent(...)の背景色と同じものに変更

//**参考リンク
**コメント [#pf976939]
#comment