"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Assign Keyboard Shortcuts to Buttons in Java?

How Can I Assign Keyboard Shortcuts to Buttons in Java?

Published on 2024-11-03
Browse:651

How Can I Assign Keyboard Shortcuts to Buttons in Java?

How to Bind a Shortcut Key to a JButton in Java

In Java, you can assign shortcut keys to buttons (e.g., clicking the "Delete" key triggers a button click) by implementing an Action, binding it to a KeyStroke, then associating the Action with the button.

To do so, follow these steps:

  1. Create an Action class that defines the behavior when the shortcut key is pressed, typically using an anonymous inner class.
  2. Register the Action with the button using a call to button.addActionListener().
  3. Map the shortcut key to the Action using InputMap and ActionMap as shown:

    • getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) retrieves the input map for keyboard events when the button panel has focus.
    • put(KeyStroke, Object) associates the desired key with the Action.
    • getActionMap().put(Object, Action) associates the Action with the mapped key.

Here's an example code snippet that implements these steps:

public class CalculatorPanel extends JPanel {
    // ... (code removed for brevity)

    for (int i = 0; i 

This code defines an Action that inserts the keystroke value into a text field when triggered. When the buttons are created, they are mapped to their respective keys on both the main and numeric keypads. As a result, pressing the corresponding keys (e.g., "1" or "NUMPAD 1") activates the associated button.

Release Statement This article is reprinted at: 1729684384 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3