在做项目时,发现在JDialog中,直接通过addKeyListener来监听回车键不起作用,无法监听到回车键,后面在网上查了些资料,终于解决了。方法如下:
KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0);
this.getRootPane().registerKeyboardAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
//do something
}
}, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
或者重写createRootPane方法,在方法里面注册keyboardaction
- @Override
- protected JRootPane createRootPane(){
- KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
- JRootPane rootPane = new JRootPane();
- rootPane.registerKeyboardAction(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- escapeKeyProc();
- }
- },stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
- return rootPane;
- }