1

我想当用户按下enter键盘上的按钮时,程序应该像单击ok按钮时一样运行。

我的代码:

public class T3 extends JFrame implements ActionListener {

JButton okBtn;

public T3() {
    this.setFocusable(true);
    this.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {
            // if enter button is pressed in keyboard, then show "Enter Button pressed" message
        }

        @Override
        public void keyPressed(KeyEvent e) {
            // if enter button is pressed in keyboard, then show "Enter Button pressed" message
        }

        @Override
        public void keyReleased(KeyEvent e) {
            //To change body of implemented methods use File | Settings | File Templates.
        }
    });
    add(createForm(), BorderLayout.NORTH);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 500);
    setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new T3();
        }
    });
}

public JPanel createForm() {
    JPanel panel = new JPanel();
    okBtn = new JButton("Ok");
    okBtn.addActionListener(this);
    panel.add(okBtn);
    return panel;
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == okBtn) {
        System.out.println("Enter Button pressed");
    }
}
}

现在,没有反应!

4

1 回答 1

3

当子组件具有焦点时,KeyListeners 不适用于容器。您将需要一个应用程序范围的 KeyListener。看看这个 SO 问题:

设置应用程序范围的 Key Listeners

于 2013-10-29T19:45:28.150 回答