Table Select All Renderer
Posted by Rob Camick on October 21, 2008
My previous entry was about using a Select All Editor in a JTable. When you double click a cell or use the F2 key to start editing a cell the editor will be displayed with the text in the cell already highlighted ready to be replaced. This is fine because the user has visual feedback that the text will be replaced if they start typing without removing the selection.
However, when you type a character when focus is still on the rendered cell the editor is invoked with the text already replaced by the character just typed. The user had no visual indication that this was going to happen.
We can provide visual feedback by using a custom renderer. The SelectAllRenderer class was designed to provide this visual feedback. It accomplishes this goal in three ways. Whenever a cell gains focus:
- the border is changed to look like the editing border
- the background of the entire cell is changed to the same background color as the cell editor
- the background of the area containing text is repainted to make it look like it is selected
Note that this is not a perfect solution as it is possible that the text may be the width of the entire cell, in which case you will not see the contrast in cell background with the selection background. Only the border will be different.
Anyway, if you decide to use the renderer it can be installed with a single line of code:
table.setDefaultRenderer(Object.class, new SelectAllRenderer());