我希望当用户按下键盘上的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");
}
}
}
现在,没有反应!
答案 0 :(得分:3)
当子组件具有焦点时,KeyListener不对容器起作用。您将需要一个应用程序范围的KeyListener。看看这个问题: