概要

Borderを変更したJTextFieldを、JTableのデフォルトセルエディタとして設定します。

サンプルコード

JTextField field = new JTextField();
field.setBorder(BorderFactory.createLineBorder(Color.RED, 2));
table.setDefaultEditor(Object.class, new DefaultCellEditor(field));
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、LineBorderを設定したJTextFieldを使用するDefaultCellEditorを作成し、JTable#setDefaultEditor(...)メソッドでObjectクラスのデフォルトセルエディタとして設定しています。

  • JTable#setDefaultEditor(...)を使用せずにJTable#prepareEditor(...)をオーバーライドしてセルエディタとして使用するコンポーネントの背景色やBorderを変更する方法もある
JTable table = new JTable(model) {
  @Override public Component prepareEditor(
        TableCellEditor editor, int row, int column) {
    Component c = super.prepareEditor(editor, row, column);
    if (c instanceof JCheckBox) {
      JCheckBox b = (JCheckBox) c;
      b.setBorderPainted(true);
      b.setBackground(getSelectionBackground());
    } else if (c instanceof JComponent
            && convertColumnIndexToModel(column) == 1) {
      ((JComponent) c).setBorder(
        BorderFactory.createLineBorder(Color.GREEN, 2));
    }
    return c;
  }
};

参考リンク

コメント