Swing/ComboCellRenderer のバックアップの現在との差分(No.7)
- category: swing folder: ComboCellRenderer title: JTableのCellRendererにJComboBoxを設定 tags: [JTable, JComboBox, TableCellRenderer, TableCellEditor] author: aterai pubdate: 2007-03-19 pubdate: 2007-03-19T02:32:35+09:00 description: JTableのCellRendererとしてJComboBoxを使用します。 image:
概要
概要
JTable
のCellRenderer
としてJComboBox
を使用します。
Screenshot
Advertisement
サンプルコード
サンプルコード
class ComboCellRenderer extends JComboBox implements TableCellRenderer {
private static final Color ec = new Color(240, 240, 255);
private final JTextField editor;
public ComboCellRenderer() {
super();
setEditable(true);
setBorder(BorderFactory.createEmptyBorder());
editor = (JTextField) getEditor().getEditorComponent();
editor.setBorder(BorderFactory.createEmptyBorder());
editor.setOpaque(true);
}
@Override public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int column) {
#spanadd
#spanend
@Override public Component getTableCellRendererComponent(
JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
removeAllItems();
if(isSelected) {
if (isSelected) {
editor.setForeground(table.getSelectionForeground());
editor.setBackground(table.getSelectionBackground());
}else{
} else {
editor.setForeground(table.getForeground());
editor.setBackground((row%2==0)?ec:table.getBackground());
editor.setBackground((row % 2 == 0) ? ec : table.getBackground());
}
addItem((value==null)?"":value.toString());
addItem(Objects.toString(value, ""));
return this;
}
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、1
列目(中央)のセルの表示をJComboBox
にするために、これを継承するセルレンダラーを設定しています。1
列目はセルエディタもJComboBox
ですが、これらは同じJComboBox
のインスタンスではなく、別々に用意しています。
解説
-
1
列目(中央)のセルの表示をJComboBox
にするために、これを継承するセルレンダラーを設定- この列のセルエディタも
JComboBox
を使用するが、セルレンダラーとは別のJComboBox
のインスタンスを設定
- この列のセルエディタも
- セルレンダラーとして使用する
JComboBox
はセルの表示のみに使用するため、以下のように設定- 表示用のアイテム(文字列)を一つだけ持つ
- 編集可にして
EditorComponent
の背景色などを他のセルと同様になるように変更 - セル内にきれいに収まるように余白を
0
に設定
JComboBox
は、セルの表示のみに使用するため、以下のように設定しています。
- 表示用のアイテム(文字列)を一つだけ持つ
- 編集可にして
EditorComponent
の背景色などを他のセルと同様になるように変更 - セル内にきれいに収まるように余白を
0
に設定