Home >Java >javaTutorial >How to Assign Shortcut Keys to JButtons in Java Using Keyboard Input?
How to Assign Shortcut Keys to JButtons in Java
Assigning shortcut keys to JButtons allows users to trigger button actions through keyboard presses, enhancing the user experience and efficiency.
Solution:
To add a shortcut key to a JButton, you need to perform the following steps:
Example:
Consider the following code snippet:
<code class="java">// Create an Action for the button Action action = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { // Perform the button's action } }; // Register the Action as a KeyStroke listener button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "delete"); button.getActionMap().put("delete", action);</code>
In this example, the Action is triggered when the Delete key is pressed while the button has focus.
Additional Resources:
The above is the detailed content of How to Assign Shortcut Keys to JButtons in Java Using Keyboard Input?. For more information, please follow other related articles on the PHP Chinese website!