在做项目时,发现在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

  1. @Override
  2. protected JRootPane createRootPane(){
  3. KeyStroke  stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0);
  4. JRootPane rootPane = new JRootPane();
  5. rootPane.registerKeyboardAction(new ActionListener() {
  6. @Override
  7. public void actionPerformed(ActionEvent e) {
  8. escapeKeyProc();
  9. }
  10. },stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);
  11. return rootPane;
  12. }
04-25 18:42