Table Select All Editor
Posted by Rob Camick on October 20, 2008
Sometimes when editing text fields it is desireable to have the text selected so that when you start typing the original text is replaced with the new text. This is easily done by adding a FocusListener to the text component and invoking the selectAll() method. Since a JTable uses a JTextField as an editor we should be able to add this text selecting feature to a table. However, it is a little more complicated then simply using a FocusListener.
A request to edit a cell can be made in one of three ways:
- by using a mouse click (usually a double click)
- by using the table edit Action which is invoked by using the F2 key
- by typing directly into a cell
Fortunately though all requests to edit a cell are handled by the editCellAt(…) method of the table. This method is also passed an EventObject which allows us to know which of the above methods was used to invoke the editor. So, by overriding the editCellAt(…) method we can access the editor and invoke the selectAll(…) method on the editor giving us the selected text in the editor. Therefore, I created the RXTable class which extends JTable and overrides this method. The RXTable class has 4 methods that allow you to control this functionality:
- setSelectAllForMouseEvent(…) – select the text on mouse events
- setSelectAllForActionEvent(…) – select the text when F2 is used
- setSelectAllForKeyEvent(…) – the first key event will invoke the editor and cause the text in the editor to be replaced with the typed key. The editor will now have focus so future key events will cause the text to be appended to the existing text in the editor.
- setSelectAllForEdit(…) – convenience method that invokes the above 3 methods.
The following line of code was used on the table shown in the image below which shows the table once the editor has been invoked: