Java Tips Weblog

  • Blog Stats

    • 1,300,722 hits
  • Categories

  • Archives

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

See Also

Key Bindings
Wrapping Actions

About these ads

4 Responses to “Table Tabbing”

  1. Anonymous said

    This was great!

  2. 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 97 other followers

%d bloggers like this: