• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JTableのCellRendererにJComboBoxを設定
#navi(../)
*JTableのCellRendererにJComboBoxを設定 [#xc6bebbb]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2007-03-19~
更新日:&lastmod;

#contents

**概要 [#pdc378a5]
JTableのCellRendererとしてJComboBoxを使用します。

#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;
   }
 }
}}
-&jnlp;
-&jar;
-&zip;

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

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

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

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