Swing/ComboBoxCellEditorInsets のバックアップ(No.8)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/ComboBoxCellEditorInsets へ行く。
- 1 (2012-11-01 (木) 18:08:14)
- 2 (2012-12-11 (火) 21:02:49)
- 3 (2014-03-19 (水) 16:29:40)
- 4 (2015-12-01 (火) 15:04:40)
- 5 (2016-12-01 (木) 14:32:05)
- 6 (2017-11-29 (水) 15:52:59)
- 7 (2019-08-02 (金) 20:56:03)
- 8 (2021-04-01 (木) 04:56:56)
- 9 (2025-01-03 (金) 08:57:02)
- 10 (2025-01-03 (金) 09:01:23)
- 11 (2025-01-03 (金) 09:02:38)
- 12 (2025-01-03 (金) 09:03:21)
- 13 (2025-01-03 (金) 09:04:02)
- category: swing
folder: ComboBoxCellEditorInsets
title: JTableのCellEditorに設定したJComboBoxに余白を追加する
tags: [JTable, TableCellEditor, TableCellRenderer, JComboBox, LayoutManager]
author: aterai
pubdate: 2012-05-07T12:28:04+09:00
description: JTableのCellEditorに設定したJComboBoxに余白を追加します。
image:
概要
JTable
のCellEditor
に設定したJComboBox
に余白を追加します。
Screenshot

Advertisement
サンプルコード
class ComboBoxPanel extends JPanel {
public final JComboBox<String> comboBox = new JComboBox<>(
new String[] {"aaaaaa", "bbb", "c"});
public ComboBoxPanel() {
super(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1.0;
c.insets = new Insets(0, 10, 0, 10);
c.fill = GridBagConstraints.HORIZONTAL;
add(comboBox, c);
comboBox.setEditable(true);
comboBox.setSelectedIndex(0);
setOpaque(true);
}
}
class ComboBoxCellRenderer extends ComboBoxPanel implements TableCellRenderer {
public ComboBoxCellRenderer() {
super();
setName("Table.cellRenderer");
}
@Override public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
this.setBackground(isSelected ? table.getSelectionBackground()
: table.getBackground());
if (value != null) {
comboBox.setSelectedItem(value);
}
return this;
}
}
View in GitHub: Java, Kotlin解説
Border
(左)JComboBox
自身に余白を設定し、これをCellRenderer
とCellEditor
に適用- ドロップダウンリストの位置、サイズが余白を含んだ幅になる
combo.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createEmptyBorder(8, 10, 8, 10), combo.getBorder()));
JPanel
+JComboBox
(右)GridBagLayout
を使用するJPanel
にJComboBox
を追加fill
フィールドをGridBagConstraints.HORIZONTAL
として、垂直方向にはJComboBox
のサイズを変更しないinsets
フィールドを設定して、JComboBox
の外側に別途(ドロップダウンリストの位置、サイズに影響しないように)余白を追加
セルの中にあるJComboBox
の幅を可変ではなく固定にする場合は、以下のようなFlowLayout
のパネルにgetPreferredSize()
をオーバーライドして幅を固定したJComboBox
を使用する方法もあります。
class ComboBoxPanel extends JPanel {
private String[] m = new String[] {"a", "b", "c"};
protected JComboBox<String> comboBox = new JComboBox<String>(m) {
@Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
return new Dimension(40, d.height);
}
};
public ComboBoxPanel() {
super();
setOpaque(true);
comboBox.setEditable(true);
add(comboBox);
}
}