- Forward


Key Bindings
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Getting Started
Back SMYC Forward
  • Purpose:
    • Allow JComponent objects to respond to the keyboard
  • Uses in the Java API:
    • Mnemonics (AbstractButton, JLabel, and JTabbedPane)
    • Accelerators (JMenutItem)
Key Bindings vs. Key Listeners
Back SMYC Forward
  • Advantages of Key Bindings:
    • Use the command pattern (i.e., Action objects) so are more maintainable
    • Don't require the JComponent to have the focus
    • Make it easy to change bindings
  • Advantages of Key Listeners:
    • Provide lower-level access (e.g., to presses and releases)
Supporting Classes
Back SMYC Forward
  • KeyStroke :
    • An encapsulation of a key action (including modifiers like Alt, Ctrl, Meta, and Shift) on a keyboard (or equivalent input device)
  • InputMap :
    • Maps/binds a KeyStroke to an Object (usually a String)
  • ActionMap :
    • Maps/binds an Action to an Object (usually a String)
Attribute of JComponent Objects
Back SMYC Forward
  • One ActionMap Object:
    • Maps/binds an Action to a String that has been mapped/bound to a KeyStroke)
  • Three InputMap Objects:
    • One for when the JComponent has the focus
    • One for when the JComponent contains (or is) the component that has the focus
    • One for when the JComponent is in the window that has the focus
The Process
Back SMYC Forward
  • The Steps:
    1. The user types a key.
    2. One or more InputMap objects is searched for a matching binding
    3. When a binding is found the ActionMap is searched for a matching Action
    4. If the Action is enabled it's actionPerformed() method is called (and the process is terminated), otherwise the search continues
  • InputMap Search Order:
    1. The focused component's WHEN_FOCUSED map
    2. The focused component's WHEN_ANCESTOR_OF_FOCUSED_COMPONENT map
    3. The WHEN_ANCESTOR_OF_FOCUSED_COMPONENT maps of enabled containers (in order)
    4. The WHEN_IN_FOCUSED_WINDOW maps (in no particular order)
An Example
Back SMYC Forward

An ArrowPad

javaexamples/keybindings/ArrowPad.java
 
An Example
Back SMYC Forward

The Action for the JButton Objects

javaexamples/keybindings/ArrowAction.java
 
An Example
Back SMYC Forward

The Action for the ActionMap

javaexamples/keybindings/ClickAction.java
 
There's Always More to Learn
Back -