CellEditorListener has "editingStopped" and "editingCancelled". But how might I implement a piece of code which needs to run when a cell editing session starts?
A typical example might be where you want the text of a JTextField editor component to go selectAll() when you start editing. I'm tempted to think the thing to do is override one of the methods of DefaultCellEditor, such as getTableCellEditorComponent or getCellEditorValue or getComponent, but none of these explicitly says they are called at the start of an edit session.
Conversely, we do know that JTable.getCellEditor returns the editor if we are editing, but null if not. This is because the component is made into a child object of JTable when editing starts. It also seems to get the focus at the beginning of an editing session, so you might perhaps think of add a FocusListener to the editor component (JTextField, etc.). But is this guaranteed? Also, maybe focus can be lost and then return during an editing session.
There's a way of listening for the "addition" (as a child object) of this editor component: ContainerListener. Unless someone tells me different this appears to be the most direct and rational way of getting a call that an editing session has begun. But it seems odd that there isn't a more direct way...
A typical example might be where you want the text of a JTextField editor component to go selectAll() when you start editing.
You can override the editCellAt(...)
method of JTable to select the text once editing has started:
@Override
public boolean editCellAt(int row, int column, EventObject e)
{
boolean result = super.editCellAt(row, column, e);
final Component editor = getEditorComponent();
if (editor != null && editor instanceof JTextComponent)
{
((JTextComponent)editor).selectAll();
if (e == null)
{
((JTextComponent)editor).selectAll();
}
else if (e instanceof MouseEvent)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
((JTextComponent)editor).selectAll();
}
});
}
}
return result;
}