• 追加された行はこの色です。
  • 削除された行はこの色です。
---
title: JTableのCellEditorにJComboBoxを設定
tags: [JTable, TableCellEditor, JComboBox, TableColumn]
author: aterai
pubdate: 2005-09-26
description: JTableのCellEditorにJComboBoxを使用し、リストから値を選択できるようにします。
---
* 概要 [#f57b6c70]
`JTable`の`CellEditor`に`JComboBox`を使用し、リストから値を選択できるようにします。

#download(https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTJy9xBM6I/AAAAAAAAAU8/h5YELRcY4gE/s800/ComboCellEditor.png)

* サンプルコード [#y53e1620]
#code(link){{
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());
}}

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

----
コンボボックスの余白を`0`にしておくと、セル内にきれいにぴったり収まります(参考:[http://www.jroller.com/page/santhosh?entry=tweaking_jtable_editing Santhosh Kumar's Weblog : Santhosh Kumar's Weblog])。

- 以下は余白を`0`にしていない場合

#ref(https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTJ1Ykl--I/AAAAAAAAAVA/ZRLgScHCF3s/s800/ComboCellEditor1.png)

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

* 参考リンク [#w85587e3]
- [http://www.jroller.com/page/santhosh?entry=tweaking_jtable_editing Santhosh Kumar's Weblog : Santhosh Kumar's Weblog]
- [[JTableのCellRendererにJComboBoxを設定>Swing/ComboCellRenderer]]
- [[JComboBoxセルエディタのドロップダウンリストを編集開始直後は表示しないよう設定する>Swing/CellEditorTogglePopup]]

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