Java: Why doesn't JTable use TableCellEditor?

jacknad picture jacknad · Nov 2, 2010 · Viewed 8.4k times · Source

The intention of MyTableCellEditor is to make a JTable cell behave like an Excel cell, IOW, entering a value after single clicking in a cell overwrites rather than appends to the existing value. I didn't expect the following code to work on the first pass, but I did expect to be hit debug breakpoints in getTableCellEditorComponent and getCellEditorValue. Why isn't getTableCellEditorComponent or getCellEditorValue called when I use jTable?

public class MyTable extends javax.swing.JFrame implements TableModelListener {
    private static final MyTableCellEditor tableCellEditor =
        new MyTableCellEditor();
        ...
    public MyTable() {
        initComponents();
        jTable.getModel().addTableModelListener(MyTable.this);
        ...
    private void initComponents() { // Generated by the Form Editor.
        jTable = new javax.swing.JTable();
        jTable.setCellEditor(tableCellEditor);
        ...
public class MyTableCellEditor extends AbstractCellEditor implements
        TableCellEditor {
    JComponent component = new JTextField();
    public Component getTableCellEditorComponent(JTable table, Object value,
            boolean isSelected, int rowIndex, int vColIndex) {
        if (isSelected) {
            ((JTextField)component).selectAll();
        }
        ((JTextField)component).setText((String)value);
        return component;
    }
    public Object getCellEditorValue() {
        return ((JTextField)component).getText();
    }
}

Answer

Mark Peters picture Mark Peters · Nov 2, 2010

setCellEditor(TableCellEditor) sets the editor for the currently active cell only (and will be lost once it's no longer active. You want to call JTable.setDefaultEditor() to set the default editor for a specific class.

jTable.setDefaultEditor(String.class, tableCellEditor);

Alternatively, you can set an editor for the column through the TableColumnModel, eg

jTable.getColumnModel().getColumn(1).setCellEditor(tableCellEditor);