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:
<code class="java">public class CalculatorPanel extends JPanel { // ... (code removed for brevity) for (int i = 0; i < 10; i++) { String text = String.valueOf(i); JButton button = new JButton(text); // ... (code removed for brevity) InputMap inputMap = buttonPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke(text), text); inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text); buttonPanel.getActionMap().put(text, numberAction); } }</code>
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.
The above is the detailed content of How Can I Assign Keyboard Shortcuts to Buttons in Java?. For more information, please follow other related articles on the PHP Chinese website!