mcardia mcardia - 1 year ago 111
Java Question

JTable Edit Cell only on double click and F2 and Not on any key press

I Have a JTable with some editable columns.

If a cell is selected and I start typing, the cell enters into edit mode.
I don´t want that.
I want to edit the cell only if I press F2 or double click it.

I found some posts about key binding, but it didn´t help.

I´m newbie in Java. please be patient and clear.

Another thing I notice. If I start editing by typing in cell, it has a different behavior than when I start edit the cell by F2 or double click.
Why is that?

Answer Source

You need to create your own TableCellEditor and overwrite the method isCellEditable:

public class MyCellEditor extends AbstractCellEditor implements TableCellEditor {

    private static final long serialVersionUID = 1L;

    JTextField textField = new JTextField("");

    public boolean isCellEditable(EventObject e) {
        if (super.isCellEditable(e)) {
            if (e instanceof MouseEvent) {
                MouseEvent me = (MouseEvent) e;
                return me.getClickCount() >= 2;
            if (e instanceof KeyEvent) {
                KeyEvent ke = (KeyEvent) e;
                return ke.getKeyCode() == KeyEvent.VK_F2;
        return false;

    public Object getCellEditorValue() {
        return this.textField.getText();

    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        return this.textField;
    return false;

In isCellEditable, I first call super.isCellEditable to check for all other reasons why a cell could be editable or not. Only if it is editable per se, we check on our conditions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download