I've added this little gem into my GUI utilities class recently. It simply adds new keys to the same system that does the [tab] focus changing:
public static void addUpDownToTraversalKeys(Component c)
{
addTraversalKeys(c, KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, KeyEvent.VK_DOWN);
addTraversalKeys(c, KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, KeyEvent.VK_UP);
}
public static void addLeftRightToTraversalKeys(Component c)
{
addTraversalKeys(c, KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, KeyEvent.VK_RIGHT);
addTraversalKeys(c, KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, KeyEvent.VK_LEFT);
}
public static void addTraversalKeys(Component c, int keysetId, int...keyCodes)
{
HashSet<AWTKeyStroke> newKeys =
new HashSet<AWTKeyStroke>(
c.getFocusTraversalKeys(keysetId));
for (int keyCode : keyCodes)
newKeys.add(AWTKeyStroke.getAWTKeyStroke(keyCode, 0));
c.setFocusTraversalKeys(keysetId,newKeys);
}
Added to my GuiUtilities class, a simply call to GuiUtilities.addUpDownToTraversalKeys(this);
inside the frame's constructor allows using the up and down arrow keys to go through all elements. Note that addLeftRightToTraversalKeys()
is not advised if you got text areas ;)