The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing  [141 examples] > Keystrokes and Input Maps  [6 examples]

e860. Listing the Key Bindings in a Component

This example demonstrates how to list all the key bindings in a component. Text components have an additional set of key bindings called a keymap. See e1005 Listing the Key Bindings in a JTextComponent Keymap for an example on how to list those key bindings.
    // List keystrokes in the WHEN_FOCUSED input map of the component
    InputMap map = component.getInputMap(JComponent.WHEN_FOCUSED);
    list(map, map.keys());
    // List keystrokes in the component and in all parent input maps
    list(map, map.allKeys());
    
    // List keystrokes in the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT input map of the component
    map = component.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    list(map, map.keys());
    // List keystrokes in all related input maps
    list(map, map.allKeys());
    
    // List keystrokes in the WHEN_IN_FOCUSED_WINDOW input map of the component
    map = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    list(map, map.keys());
    // List keystrokes in all related input maps
    list(map, map.allKeys());
    
    public static void list(InputMap map, KeyStroke[] keys) {
        if (keys == null) {
            return;
        }
        for (int i=0; i<keys.length; i++) {
            // This method is defined in e859 Converting a KeyStroke to a String
            String keystrokeStr =  keyStroke2String(keys[i]);
    
            // Get the action name bound to this keystroke
            while (map.get(keys[i]) == null) {
                map = map.getParent();
            }
            if (map.get(keys[i]) instanceof String) {
                String actionName = (String)map.get(keys[i]);
            } else {
                Action action = (Action)map.get(keys[i]);
            }
        }
    }

 Related Examples
e858. Creating a KeyStroke and Binding It to an Action
e859. Converting a KeyStroke to a String
e861. Sharing an InputMap or an ActionMap Between Two Components
e862. Finding a Key Binding in a Component
e863. Adding an InputMap to a Component

See also: Actions    JButton    JCheckBox    JComboBox    JDesktop and JInternalFrame    JFrame, JWindow, JDialog    JLabel    JList    JProgressBar    JRadioButton    JScrollPane    JSlider    JSpinner    JSplitPane    JTabbedPane    JToolBar    Layout    Look and Feel    Menus    Progress Monitor    The Screen    Tool Tips    UI Default Values   


© 2002 Addison-Wesley.