概要

JTreeのノードにある文字列の左右に余白を追加します。

サンプルコード

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の場合のみ対応

参考リンク

コメント