如何将键绑定到 JButton?

How do I bind a key to a JButton?

我有一个简单的 JButton 链接到 actionPerformed 方法。现在我想给按钮绑定一个键,这样当我在键盘上按下这个键时,它会执行与用鼠标按下按钮时相同的操作。

我发现此代码有效,但如您所见,我必须编写两次代码才能在按下键或按钮时执行。

有没有办法避免这种情况?

import java.io.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.*;


public class provakey implements ActionListener{

    private JButton bStart;                                         
    
    //Costruttore
    public provakey() throws IOException{
        initGUI();
    }

    private void initGUI(){
        JFrame frame = new JFrame();
        JPanel buttonPanel = new JPanel();
        bStart = new JButton("Avvia");
        bStart.addActionListener(this);
        bStart.setActionCommand("start");
        bStart.setBounds(140,10,150,40);

        AbstractAction buttonPressed = new AbstractAction() {   
            @Override
            public void actionPerformed(ActionEvent e) {
                if (bStart.isEnabled()){

                System.out.println("pressed");
                }
            }
        };
        bStart.getActionMap().put("start", buttonPressed);
        bStart.getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).
                put(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A,0), "start");

        buttonPanel.setLayout(null);
        buttonPanel.setBounds(0,240,600,60);
        buttonPanel.add(bStart);
        frame.setLayout(null);
        frame.add(buttonPanel);
        frame.setTitle("Prova");
        frame.setSize(600, 350);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if ("start".equals(e.getActionCommand())) { 
            buttonPressed();
        }
    }

    public void buttonPressed(){
        System.out.println("pressed");
    }

    public static void main (String args[]) throws IOException {
        provakey p = new provakey();
    }
}

I have to write twice the code to perform when key is pressed or button is pressed.

ActionActionListener

所以,你可以给按钮添加一个Action,这样无论你点击按钮还是使用按键绑定都会执行相同的Action:

//bStart.addActionListener(this);
bStart.addActionListener( buttonPressed );

无需设置操作命令,因为您现在有一个唯一的 class 用于“开始”处理,class 中的其他按钮不共享该处理。

有关工作示例,请参阅: