event
GetFocusTraversalKeys example
In this example we are going to see how to get the focus traversal keys of an input device in a Java Desktop Application.
This is quite simple and to do it you have to follows these steps
- Create an input device like an
JButton. - Create a new
HashSetto hold AWTKeyStroke objects. - Use the
JButton.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS)call to get theFocusTraversalKeysof that input device. - Use
JButton.add(KeyStroke.getKeyStroke("P"))to add a keystroke to the button. - Use the
JButton.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, s)to set FocusTraversalKeys of these device.
Let’s see the code:
package com.javacodegeeks.snippets.desktop;
import java.awt.AWTKeyStroke;
import java.awt.KeyboardFocusManager;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.KeyStroke;
public class Main {
public static void main(String[] argv) throws Exception {
JButton jButton = new JButton("a");
Set<AWTKeyStroke> s = new HashSet<AWTKeyStroke>(jButton.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
s.add(KeyStroke.getKeyStroke("P"));
jButton.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, s);
}
}
This was an example on how to get FocusTraversalKeys in Java.

