如何在 Java 中使用 JButton 的快捷键
为 JButton 分配快捷键时,您希望按钮能够响应当没有鼠标按下某个键时。这可以通过为按钮创建一个操作来实现。然后,Action 由 ActionListener 配置,并连接到 KeyStroke。
请参阅 Swing 教程以获取各种资源,包括以下部分:
示例:
<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>
以上是如何使用 Java 中的操作为 JButton 分配快捷键?的详细内容。更多信息请关注PHP中文网其他相关文章!