TITLE:JTableのCellRendererにJComboBoxを設定
#navi(../)
RIGHT:Posted by [[terai]] at 2007-03-19
*JTableのCellRendererにJComboBoxを設定 [#xc6bebbb]
JTableのCellRendererとしてJComboBoxを使用します。

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

#screenshot

**サンプルコード [#l43fa315]
#code{{
class ComboCellRenderer extends JComboBox implements TableCellRenderer {
  private static final Color ec = new Color(240, 240, 255);
  private final JTextField editor;
  public ComboCellRenderer() {
    super();
    setEditable(true);
    setBorder(BorderFactory.createEmptyBorder());

    editor = (JTextField) getEditor().getEditorComponent();
    editor.setBorder(BorderFactory.createEmptyBorder());
    editor.setOpaque(true);
  }
  public Component getTableCellRendererComponent(JTable table, Object value,
                           boolean isSelected, boolean hasFocus,
                           int row, int column) {
    removeAllItems();
    if(isSelected) {
      editor.setForeground(table.getSelectionForeground());
      editor.setBackground(table.getSelectionBackground());
    }else{
      editor.setForeground(table.getForeground());
      editor.setBackground((row%2==0)?ec:table.getBackground());
    }
    addItem((value==null)?"":value.toString());
    return this;
  }
}
}}

**解説 [#k4fd12f0]
上記のサンプルでは、1列目(中央)のセルの表示をJComboBoxにするために、これを継承するセルレンダラーを設定しています。1列目はセルエディタもJComboBoxですが、これらは同じJComboBoxのインスタンスではなく、別々に用意しています。

レンダラーで使用するJComboBoxは、セルの表示のみに使用するため、以下のように設定しています。
-表示用のアイテム(文字列)を一つだけ持つ
-編集可にしてEditorComponentの背景色などを他のセルと同様になるように変更
-セル内にきれいに収まるように余白を0に設定

**参考リンク [#ta6ab55a]
-[[JTableのCellEditorにJComboBoxを設定>Swing/ComboCellEditor]]

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