Search code examples
javaswingjtablejtextfieldtablecelleditor

TableCellEditor: clear original text if key is pressed; retain value if no input was givien


I have here a code I found in the stackoverflow which allows the table to have a custom cell editor as JTextField.

I have been reading some of the articles about cell editor and I understand some the behavior of each abstract method.

class tableText extends AbstractCellEditor implements TableCellEditor {
JComponent component = new JTextField();

public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,int rowIndex, int vColIndex) {
    ((JTextField) component).setText((String) value);
    return component;
}

public Object getCellEditorValue() {
    return ((JTextField) component).getText();
}

}

This code allowed me to add a JTextField when I want to edit a cell in my table but I am looking to add some code to it but Im not exactly sure where to put them.

The behavior I wanted to add was this:

When the cell is clicked and the JTextField appears, if the user pressed a numerical key, it will replace the old value with a new one.

If the cell's value was left blank, the original value will be retained.

I know how to make these codes, but I'm not sure where to put them.

Anyone can guide me on this?


Solution

    1. If the user pressed a numeric key, it will replace the old value with a new one.

      As shown here, you should use a DefaultCellEditor with a JTextField for your cell editor. Override the table's editCellAt() method and select the editor's text so that the old value will be replaced immediately as the user types.

      final Component editor = getEditorComponent();
      …
      ((JTextComponent) editor).selectAll();
      

      If necessary, add a DocumentListener to examine individual keystrokes or a DocumentFilter to enforce numeric entry.

    2. If the cell's value was left blank, the original value will be retained.

      Press the Escape key to cancel editing and restore the original value.

    image