我想在单击jbutton时立即按“ Enter”键时执行一些操作,但它不起作用,有人帮忙

这是我的代码



    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

      jButton.keyTyped(e);

    } 





按键监听器功能



    public void keyTyped(KeyEvent e) {
        //action
    }

最佳答案

您需要绑定它-下面的示例代码。

public class Test {

    static JButton btnA = new JButton("A");
    static JPanel jp = new JPanel();
    static JFrame jf = new JFrame("test frame");

    static ActionListener action = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jl.setText(((JButton)e.getSource()).getText());
        }
    };

    public static void main(String[] args) {
        jf.setVisible(true);
        jf.setSize(400, 400);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jp.add(btnA);
        jf.add(jp);

        btnA.addActionListener(action);
    }
}

10-05 19:39