如何将键绑定到 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();
    }
}

解决方法

我必须编写两次代码才能在按下键或按下按钮时执行。

ActionActionListener

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

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

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

请参阅:https://stackoverflow.com/a/33739732/131872 以获取工作示例。