我想当用户按下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");
}
}
}
现在,没有反应!