---
title: JListで異なる高さのセルを使用
tags: [JList, JTextArea, ListCellRenderer]
author: aterai
pubdate: 2006-05-15T09:36:24+09:00
description: JListのレンダラーにJTextAreaを使って、異なる高さのセルを作成します。
---
* 概要 [#v5f5cc63]
`JList`のレンダラーに`JTextArea`を使って、異なる高さのセルを作成します。

#download(https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTK2Z8UOTI/AAAAAAAAAWo/7GoDkuVX8Fc/s800/DifferentCellHeight.png)

* サンプルコード [#r38aaded]
#code(link){{
class TextAreaRenderer extends JTextArea implements ListCellRenderer<String> {
  private Border focusBorder;
  private static final Border NOMAL_BORDER =
    BorderFactory.createEmptyBorder(2, 2, 2, 2);
  private static final Color EVEN_COLOR = new Color(230, 255, 230);
  @Override public Component getListCellRendererComponent(
      JList list, String str, int index,
      boolean isSelected, boolean cellHasFocus) {
    //setLineWrap(true);
    setText(Objects.toString(str, ""));
    if (isSelected) {
      setBackground(list.getSelectionBackground());
      setForeground(list.getSelectionForeground());
    } else {
      setBackground(index % 2 == 0 ? EVEN_COLOR : list.getBackground());
      setForeground(list.getForeground());
    }
    if (cellHasFocus) {
      if (focusBorder == null) {
        focusBorder = new DotBorder(
            new Color(~list.getSelectionBackground().getRGB()), 2);
      }
      setBorder(focusBorder);
    } else {
      setBorder(NOMAL_BORDER);
    }
    return this;
  }
}

private DefaultListModel makeList() {
  DefaultListModel model = new DefaultListModel();
  model.addElement("一行");
  model.addElement("一行目\n二行目");
  model.addElement("一行目\n二行目\n三行目");
  model.addElement("四行\n以上ある\nテキスト\nの場合");
  return model;
}
}}

* 解説 [#deb3ece5]
左が複数行に対応した`JList`、右が通常の`JList`になります。左の`JList`では、`JList#getFixedCellHeight()`が`-1`で、`ListCellRenderer`に`JTextArea`を使用しているため、テキストに`\n`を含めることで複数行を作成することができます。

セルの区切りを分かりやすくするために、偶数奇数で行の背景色を変更しています。

`JTextArea`にセルフォーカスがある状態を表現するために、`LineBorder`を継承して作成した`DotBorder`を使用しています。

#code{{
class DotBorder extends LineBorder {
  public DotBorder(Color color, int thickness) {
    super(color, thickness);
  }
  @Override public boolean isBorderOpaque() {
    return true;
  }
  @Override public void paintBorder(
      Component c, Graphics g, int x, int y, int w, int h) {
    Graphics2D g2 = (Graphics2D) g;
    g2.translate(x, y);
    g2.setPaint(getLineColor());
    BasicGraphicsUtils.drawDashedRect(g2, 0, 0, w, h);
    g2.translate(-x, -y);
  }
}
}}

* 参考リンク [#l382633c]
- [http://docs.oracle.com/javase/jp/8/api/docs/javax/swing/JList.html#setFixedCellHeight-int- JList#setFixedCellHeight(int) (Java Platform SE 8)]

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