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:
Map the shortcut key to the Action using InputMap and ActionMap as shown:
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.
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