Search code examples
javajtablearrow-keys

How to enable using arrows keys to move row selection in JTable?


I noticed that I can you arrows to move row selection of my JTable object only when I press tab key. Is it possible to use arrows after row selection by mouse-click (instead of using TAB)?


Solution

  • In order for the arrow keys to change row selection, the JTable must have focus. Pressing the tab key changes focus to the next (or first) "focussable" Component on the page which is likely a SubComponent in the JTable.

    To get it to focus automatically when it becomes visible, add a ComponentListener with the an componentShown(...) method implemented to call the JTable's requestFocusInWindow() method.

    Is it possible to use arrows after row selection by mouse-click (instead of using TAB)

    Yes; if you click the mouse on a row, that should also focus the row, allowing you to use the arrow keys as well.

    Updated: corrected method used to get input focus, with thanks to camickr (see comments)