Swing/TreeBackgroundSelectionColor のバックアップソース(No.3)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- バックアップ を表示
- Swing/TreeBackgroundSelectionColor へ行く。
- 1 (2012-12-06 (木) 12:11:56)
- 2 (2012-12-07 (金) 16:38:57)
- 3 (2013-01-29 (火) 23:38:50)
- 4 (2015-01-06 (火) 16:52:09)
- 5 (2016-06-24 (金) 19:44:21)
- 6 (2017-09-22 (金) 08:40:20)
- 7 (2019-04-02 (火) 17:25:19)
- 8 (2021-01-13 (水) 18:01:51)
- 9 (2023-07-20 (木) 13:11:54)
- 10 (2025-01-03 (金) 08:57:02)
- 11 (2025-01-03 (金) 09:01:23)
- 12 (2025-01-03 (金) 09:02:38)
- 13 (2025-01-03 (金) 09:03:21)
- 14 (2025-01-03 (金) 09:04:02)
- 15 (2025-06-19 (木) 12:41:37)
- 16 (2025-06-19 (木) 12:43:47)
TITLE:JTreeの選択背景色を変更 #navi(../) #tags(JTree, TreeCellRenderer) RIGHT:Posted by &author(aterai); at 2012-10-29 *JTreeの選択背景色を変更 [#qafe3f1f] ``JTree``のノード条件によって、その選択背景色を変更します。 -&jnlp; -&jar; -&zip; //#screenshot #ref(https://lh4.googleusercontent.com/-7JA4jpNa55U/UI1VhdHlkwI/AAAAAAAABVw/dAUHGh4q014/s800/TreeBackgroundSelectionColor.png) **サンプルコード [#e9085f3e] #code(link){{ class SelectionColorTreeCellRenderer extends DefaultTreeCellRenderer { @Override public Component getTreeCellRendererComponent( JTree tree, Object value, boolean isSelected, boolean expanded, boolean leaf, int row, boolean hasFocus) { JComponent c = (JComponent)super.getTreeCellRendererComponent( tree, value, isSelected, expanded, leaf, row, hasFocus); if(isSelected) { setParticularCondition(value); c.setForeground(getTextSelectionColor()); c.setBackground(getBackgroundSelectionColor()); if(leaf && value.toString().startsWith("a")) { c.setOpaque(true); c.setBackground(Color.RED); }else{ c.setOpaque(false); c.setBackground(getBackgroundSelectionColor()); } }else{ c.setForeground(getTextNonSelectionColor()); c.setBackground(getBackgroundNonSelectionColor()); } return c; } private Color color = null; private void setParticularCondition(Object value) { if(value instanceof DefaultMutableTreeNode) { Object uo = ((DefaultMutableTreeNode)value).getUserObject(); if(uo instanceof Color) { color = (Color)uo; return; } } color = null; } @Override public Color getBackgroundSelectionColor() { return color!=null ? color : super.getBackgroundSelectionColor(); } } }} **解説 [#dfd16025] 上記のサンプルでは、以下の条件でノードの選択背景色を変更しています。 - ``DefaultMutableTreeNode#getUserObject()``が``Color``の場合、その色を選択背景色に変更 -- ``DefaultTreeCellRenderer#getBackgroundSelectionColor()``をオーバーライド -- ノードアイコンの背景は選択状態にならず、ノードテキストの背景色のみ変更される - ノードテキストが "a" で始まる場合、選択背景色を``Color.RED``に変更 -- ``TreeCellRenderer#getTreeCellRendererComponent(...)``で取得したコンポーネント(=``JLabel``)を``setOpaque(true)``で不透明、``setBackground(Color.RED)``で背景色を赤に変更 -- ノードアイコン、テキストの背景色が共に選択状態になる ``Synth Look & Feel``で作成されている``Nimbus``などでは、上記のような選択背景色にならない場合があります。 //**参考リンク **コメント [#cf353b4a] #comment