• title: JTableのCellEditorにJComboBoxを設定 tags: [JTable, TableCellEditor, JComboBox, TableColumn] author: aterai pubdate: 2005-09-26 description: JTableのCellEditorにJComboBoxを使用し、リストから値を選択できるようにします。

概要

JTableCellEditorJComboBoxを使用し、リストから値を選択できるようにします。

サンプルコード

JComboBox cb = new JComboBox(new String[] {"名前0", "名前1", "名前2"});
cb.setBorder(BorderFactory.createEmptyBorder());

TableColumn col = table.getColumnModel().getColumn(1);
col.setCellEditor(new DefaultCellEditor(cb));
//col.setCellRenderer(new ComboBoxCellRenderer());
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、1列目のセルエディタとしてコンボボックスを使うDefaultCellEditorを登録しています。


コンボボックスの余白を0にしておくと、セル内にきれいにぴったり収まります(参考:Santhosh Kumar's Weblog : Santhosh Kumar's Weblog)。

  • 以下は余白を0にしていない場合
ComboCellEditor1.png

セルの表示にもJComboBoxを使用する場合は、JTableのCellRendererにJComboBoxを設定を参考にJComboBoxを継承するセルレンダラーを使用してみてください。

参考リンク

コメント