JTreeのノードの文字列に余白を追加
Total: 5957
, Today: 1
, Yesterday: 1
Posted by aterai at
Last-modified:
概要
JTree
のノードにある文字列の左右に余白を追加します。
Screenshot
Advertisement
サンプルコード
class MyTreeCellRenderer2 extends DefaultTreeCellRenderer {
private final JPanel p = new JPanel(new BorderLayout());
private final JLabel icon = new JLabel();
private final JLabel text = new JLabel();
private final Border innerBorder = BorderFactory.createEmptyBorder(1, 2, 1, 2);
private final Border emptyBorder = BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(1, 1, 1, 1), innerBorder);
private final Border hasFocusBorder;
private final TreeCellRenderer renderer;
public MyTreeCellRenderer2(TreeCellRenderer renderer) {
super();
this.renderer = renderer;
Color bsColor = getBorderSelectionColor();
Color focusBGColor = new Color(~getBackgroundSelectionColor().getRGB());
hasFocusBorder = BorderFactory.createCompoundBorder(
new DotBorder(focusBGColor, bsColor), innerBorder);
icon.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 2));
text.setBorder(emptyBorder);
text.setOpaque(true);
p.setOpaque(false);
p.add(icon, BorderLayout.WEST);
p.add(text);
}
@Override public Component getTreeCellRendererComponent(
JTree tree, Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
JLabel l = (JLabel) renderer.getTreeCellRendererComponent(
tree, value, selected, expanded, leaf, row, hasFocus);
Color bColor, fColor;
if (selected) {
bColor = getBackgroundSelectionColor();
fColor = getTextSelectionColor();
} else {
bColor = getBackgroundNonSelectionColor();
fColor = getTextNonSelectionColor();
if (bColor == null) bColor = getBackground();
if (fColor == null) fColor = getForeground();
}
text.setForeground(fColor);
text.setBackground(bColor);
text.setBorder(hasFocus ? hasFocusBorder : emptyBorder);
text.setText(l.getText());
icon.setIcon(l.getIcon());
return p;
}
}
View in GitHub: Java, Kotlin解説
- 左
Default
- 中
DefaultTreeCellRenderer#paint(...)
メソッドをオーバーライドして余白を追加WindowsLookAndFeel
(フォーカスのボーダーがアイコンの周りには描画されない)でgetComponentOrientation().isLeftToRight()==true
の場合のみ対応
- 右
DefaultTreeCellRenderer#getTreeCellRendererComponent(...)
メソッドをオーバーライドしてアイコンと文字列を別のJLabel
に分解し、文字列にのみBorderFactory.createEmptyBorder(0, 0, 0, 2)
で余白を追加WindowsLookAndFeel
(フォーカスのボーダーがアイコンの周りには描画されない)でgetComponentOrientation().isLeftToRight()==true
の場合のみ対応