JTableのCellEditorに設定したJComboBoxに余白を追加する
Total: 6892, Today: 3, Yesterday: 2
Posted by aterai at
Last-modified:
Summary
JTableのCellEditorに設定したJComboBoxに余白を追加します。
Screenshot

Advertisement
Source Code Examples
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, KotlinDescription
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);
}
}