Home >Java >javaTutorial >How Can I Assign a Shortcut Key to a JButton Using an Action in Java?
How to Use a Shortcut Key for a JButton in Java
When assigning a shortcut key to a JButton, you want the button to respond when a certain key is pressed without the mouse. This can be achieved by creating an Action for the button. The Action is then configured by the ActionListener, and connected to a KeyStroke.
Refer to the Swing tutorial for a wide range of resources, including sections on:
Example:
<code class="java">import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class CalculatorPanel extends JPanel { // Use Action here private JTextField display; public CalculatorPanel() { // Implement Action here Action numberAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { display.replaceSelection(e.getActionCommand()); } }; setLayout( new BorderLayout() ); display = new JTextField(); display.setEditable( false ); display.setHorizontalAlignment(JTextField.RIGHT); add(display, BorderLayout.NORTH); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout(0, 5) ); add(buttonPanel, BorderLayout.CENTER); for (int i = 0; i </code>
The above is the detailed content of How Can I Assign a Shortcut Key to a JButton Using an Action in Java?. For more information, please follow other related articles on the PHP Chinese website!