Mega Code Archive

 
Categories / Java Tutorial / Swing Event
 

KeyboardFocusManager

Tab and Shift-Tab are used for keyboard focus traversal. To define your own traversal keys: replace or append to a key set via the setFocusTraversalKeys() method of Component. FORWARD_ TRAVERSAL_KEYS, BACKWARD_TRAVERSAL_KEYS, and UP_CYCLE_TRAVERSAL_KEYS constants of KeyboardFocusManager are for forward, backward, and up-cycle. To add the 'A' key as an up-cycle key for a component import java.awt.AWTKeyStroke; import java.awt.KeyboardFocusManager; import java.util.HashSet; import java.util.Set; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.KeyStroke; public class KeyboardFocusManagerDemo {   public static void main(String[] args) {     JFrame aWindow = new JFrame("This is a Border Layout");     aWindow.setBounds(30, 30, 300, 300); // Size     aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     JPanel p = new JPanel();     p.add(new JTextField(10));     Set<AWTKeyStroke> set = p.getFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS);     set = new HashSet(set);     KeyStroke up = KeyStroke.getKeyStroke("A");     set.add(up);     System.out.println(set);     p.setFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, set);     aWindow.add(p);     aWindow.setVisible(true); // Display the window   } }