MyTableCellEditor needs to add overwrite editing (like an Excel cell) and data entry rules (parseDouble) to JTable. Why does the cell erase the user entered value when the user clicks into another cell? IOW: the value that is entered into a cell is visible until another cell is clicked, then it is gone. Stepping through the program, getTableCellEditorComponent is called when when a cell value is edited by the user and getCellEditorValue is called when cell editing is completed.
public class MyTableFrame extends javax.swing.JFrame
implements TableModelListener {
private static TableColumn column2;
public MyTableFrame() {
initComponents();
...
column2 = jTable.getColumnModel().getColumn(2);
column2.setCellEditor(new MyTableCellEditor());
jTable.getModel().addTableModelListener(this);
}
}
public class MyTableCellEditor extends AbstractCellEditor implements
TableCellEditor {
// Component to handle the editing of a cell value
private JTextField component = new JTextField();
// Return value
private Object value;
private DefaultTableModel model;
private int rowIndex;
private int columnIndex;
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int rowIndex, int columnIndex) {
model = (DefaultTableModel) table.getModel();
this.value = value;
this.rowIndex = rowIndex;
this.columnIndex = columnIndex;
component.setText("");
return component;
}
public Object getCellEditorValue() {
try {
return Double.parseDouble(model.getValueAt(rowIndex, columnIndex)
.toString());
} catch (Exception ex) {
return value;
}
}
}
I guess the entry is made into the model after the editing is complete. So getting the value from the model in getCellEditorValue()
will give you the value before the edit.
Instead you should use component.getText()
to fetch the value.
return Double.parseDouble(component.getText())