Start editing in a cell in JTable on gaining focus

zerone picture zerone · Aug 7, 2012 · Viewed 7.5k times · Source

I have defined cell editors for the two columns in my table in the following manner:

Java Code:

JComboBox combo = new JComboBox();
//code to add items to the combo box goes here.

JTextField textField = new JTextField();
textField.setHorizontalAlignment(JTextField.RIGHT);

TableColumn column = myJTable.getColumnModel().getColumn(0);
column.setCellEditor(new DefaultCellEditor(combo));

column = myJTable.getColumnModel().getColumn(1);
column.setCellEditor(new DefaultCellEditor(textField));

The problem I am facing is that when a focus is moved to a table cell, the cell doesn't become automatically editable. So, when the focus is moved to column 2 (that has a text field as an editor), the caret sign doesn't not appear unless the cell is double-clicked or the user starts typing. Similar is the case for column 1 (that has a combo box as an editor) as here the combo box doesn't appear unless the cell is clicked. These behaviors are counter-intuitive and undesirable for a user operating with the keyboard.:(

Please suggest pointers on how this could be resolved.

Thanks in advance.

Answer

trashgod picture trashgod · Aug 7, 2012
  1. This example overrides editCellAt() in a JTable having a DefaultCellEditor using JTextField.

  2. You can bind the Space key to the startEditing action defined for JTable:

    table.getInputMap().put(
        KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "startEditing");