How do I register focusGained and focusLost events on individual cells of a JTable?

Sandip Chitale

You will have to subclass JTable and override the following three methods -

  • public Component prepareEditor(TableCellEditor editor,int row, int column)
    Prepares the editor by querying the data model for the value and selection state of the cell at row, column.
  • public void editingCanceled(ChangeEvent e)
    Invoked when editing is canceled. The editor object is discarded and the cell is rendered once again.
  • public void editingStopped(ChangeEvent e)
    Invoked when editing is finished. The changes are saved and the editor is discarded.

In the prepareCellEditor first call the super.prepareCellEditor(...). On the returned component add the FocusListener.

Now whenever the editor component gets focus the focusGained(..) of the focus listener will be called. Ditto for focus loss.

In the editingCancelled(..) and editingStopped(...) remove the FocusListener.