JTableのCellEditorにJComboBoxを設定

編集者:Terai Atsuhiro~

作成日:2005-09-26
更新日:2021-11-07 (日) 05:32:39
  • category: swing folder: ComboCellEditor title: JTableのCellEditorにJComboBoxを設定 tags: [JTable, TableCellEditor, JComboBox, TableColumn] author: aterai pubdate: 2005-09-26T15:27:12+09:00 description: JTableのCellEditorにJComboBoxを使用し、リストから値を選択できるようにします。 image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTJy9xBM6I/AAAAAAAAAU8/h5YELRcY4gE/s800/ComboCellEditor.png

概要

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

概要

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

サンプルコード

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

#spandel
http://terai.xrea.jp/swing/combocelleditor/screenshot.png
#spanend
#spanadd
TableColumn col = table.getColumnModel().getColumn(1);
#spanend
#spanadd
col.setCellEditor(new DefaultCellEditor(cb));
#spanend
#spanadd
// col.setCellRenderer(new ComboBoxCellRenderer());
#spanend
#spanadd
View in GitHub: Java, Kotlin

サンプルコード

JComboBox combo = new JComboBox();
combo.setBorder(BorderFactory.createEmptyBorder());
combo.addItem("名前0");
combo.addItem("名前1");
combo.addItem("名前2");
table.setDefaultEditor(JComboBox.class, new DefaultCellEditor(combo));

解説

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

解説

コンボボックスを使うDefaultCellEditorオブジェクトを生成し、JTable#setDefaultEditorメソッドでこれをJComboBox.classのエディタに設定しています。

参考リンク

エディタに設定するコンボボックスの余白を0にしておくと、セルにきれいに収まります(参考:Santhosh Kumar's Weblog : Santhosh Kumar's Weblog)。

参考リンク

コメント

コメント