Table Tabbing
Posted by Rob Camick on November 4, 2008
The default Tab Action in a JTable causes focus to move to the next cell. When the end of line is reached focus move to the first cell of the next line. When the end of the table is reached focus moves to the top of the table. There may be times when you want to change this default behaviour.
For example, maybe you want focus to move to the next editable cell in the table. Do you really need to write a custom Tab Action from scratch or can you leverage the functionality of the default Tab Action? If you have read my previous entry on Wrapping Actions then you know the answer, if not then maybe now is a good time to take a quick read. We will attempt to use the functionality of the default Tab Action to satisfy this requirement.
All we really need to do is create a loop and keep invoking the default Tab Action until focus is on an editable cell. The EditableCellFocusAction class does exactly this. It is easily installed with a single line of code:
new EditableCellFocusAction(table, KeyStroke.getKeyStroke("TAB"));
Why stop there we can use this Action for other KeyStrokes as well:
new EditableCellFocusAction(table, KeyStroke.getKeyStroke("shift TAB"));
new EditableCellFocusAction(table, KeyStroke.getKeyStroke("RIGHT"));
new EditableCellFocusAction(table, KeyStroke.getKeyStroke("LEFT"));
new EditableCellFocusAction(table, KeyStroke.getKeyStroke("UP"));
new EditableCellFocusAction(table, KeyStroke.getKeyStroke("DOWN"));
Hopefully this give an example of how easy it can be to replace a default Action with a custom Action while still using the functionality of the default Action.
Get The Code
EditableCellFocusAction.java
WrappedAction.java
Anonymous said
This was great!
Rob Camick said
Glad it helped.
Daniel said
I think the correct solution is here: http://stackoverflow.com/a/12157344/140278
Rob Camick said
That is the correct solution for the specific problem asked in that question. However, this blog entry addresses different functionality. This suggestion is used for handling focus within cells of a given table.