Search code examples
javaswingjtablejtextfieldtablecelleditor

JTable editor keep old values


Ok, I notice a problem with my editor in JTable. The scenario looks like this :

  • I edit a cell and enter a valid value, lets say I enter 42
  • I double click on an other cell (which can be empty or not)
  • The cell now contain 42, I can edit this value but as I double click on the cell 42 is in the cell.

I suspect my editor because when I use DefaultCellEditor there is no problem. Here is its declaration :

public class GlobalEditor extends DefaultCellEditor {
public GlobalEditor(JTable table, JTextField jtf) {
    super(jtf);
    /*
     * Setting font, background/foreground color, center alignement
     */
}

public boolean stopCellEditing() {
    String value = ((JTextField) getComponent()).getText();
    if (!value.equals("")) {
        if (value.length() > 10) {
            ((JComponent) getComponent()).setBorder(new LineBorder(Color.red));
            return false;
        }
    }
    return super.stopCellEditing();
}

@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    JTextField ec = (JTextField) editorComponent;
    if(value != null && value+"" != "---")
        ec.setText(""+value);
    if (isSelected) {
        ec.selectAll();
    }

    return editorComponent;
}

}

This line this.setDefaultEditor(Object.class, new GlobalEditor(this, new JTextField())); sets my editor in my JTable constructor.

What am I missing ?


Solution

  • Ok this worked :

    JTextField ec = (JTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column);
    

    Instead of (also return ec instead of editorComponent) :

    JTextField ec = (JTextField) editorComponent;
    

    In the getTableCellEditorComponent method.

    Any explanation is welcomed !