From: stormreaver
Written: 2009-04-27 09:24:46.422626
Subject: Invoking A JTable Cell Editor Programmatically

To invoke the editor within a JTable cell programmatically, you need to do two things:

1) Call JTable.editCellAt(row,cell);
2) Explicitly call requestFocus() on the editor component within the cell editor.

Here's an example for a cell in which you create a JTextField as the cell editor component.

1) Set the JTextField as the cell editor for a column within the JTable. This code was taken from a tax management program I wrote:


JTextField m_txtParcelEditor = new JTextField();

protected class ParcelNumberEditor extends DefaultCellEditor
{
public ParcelNumberEditor()
{
super(m_txtParcelEditor);
}
}

protected void setParcelNumberCellEditor()
{
TableColumn col = m_tblMain.getColumnModel().getColumn(1);

col.setCellEditor(new ParcelNumberEditor());
}


The above code creates a cell editor subclass using an existing JTextField as the editor component.


2) In my program, whenever a key other than a special (to my program) control key is pressed within column 1 of the JTable, the cell editor for column one is invoked:

m_tblMain.editCellAt(m_tblMain.getSelectedRow(), m_tblMain.getSelectedColumn());
m_txtParcelEditor.requestFocus();

The requestFocus() call is crucial, as the custom editor component (m_txtParcelEditor, in this case) will not respond to keyboard or focus events without it. In my program, when the enter or tab keys are pressed, or the editor component loses focus, information is automatically loaded from the database. This requires the editor component to have keyboard focus.
You must register an account before you can reply.