如何为 java.awt.Frame 进行键绑定?

2022-01-24 00:00:00 key-bindings java swing jframe keylistener

我的窗口是一个 java.awt.Frame,Frame 内部是两个面板 (java.awt.Panel).我正在尝试让窗口处理我按下的按钮.

My window is a java.awt.Frame, and inside of the Frame are two Panels (java.awt.Panel). I'm trying to make it so that the window handles buttons I press.

我尝试使用 KeyListener,使 Frame 实现 KeyListener.我将 KeyListener 添加到 Frame 中,但是当我按下键时 KeyListener 函数没有做任何事情.(我尝试使用 System.out.println() 进行打印.)

I tried using a KeyListener, making the Frame implement the KeyListener. I added the KeyListener to the Frame, but the KeyListener functions didn't do anything when I pressed keys. (I tried printing with System.out.println().)

我尝试按照本教程进行操作:http://tips4java.wordpress.com/2008/10/10/键绑定/ .这是我尝试处理按空格键的操作:

I tried following this tutorial: http://tips4java.wordpress.com/2008/10/10/key-bindings/ . Here is the my attempt to handle pressing the SPACEBAR:

public void registerActions(){                                  //01
  Action myAction = new AbstractAction(){                       //02
    @Override                                                   //03
    public void actionPerformed(ActionEvent e) {                //04
      System.out.println("GREAT SUCCESS!");                     //05
    }                                                           //06
  };                                                            //07
  KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0); //08
  component.getInputMap().put(key, "myAction");                 //09
  component.getActionMap().put("myAction", myAction);           //10
}                                                               //11

主要问题是我不知道第 09 行中的组件"应该是什么10,因为我的应用程序没有任何 JComponents.

The main problem is that I don't know what 'component' should be in lines 09 & 10, because my application does not have any JComponents.

有没有办法在不使用摆动组件的情况下做到这一点?还是有其他处理按键的方法?

Is there a way to do this without using swing components? Or is there another way to handle key presses?

推荐答案

我发现我可以使用 AWTEventListener 来做到这一点.

I found that I could do this with an AWTEventListener.

public class MyFrame extends Frame implements AWTEventListener {

  ...

  public MyFrame(String title){
    super(title);
    ...
    this.getToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK);
  }

  @Override
  public void eventDispatched(AWTEvent event) {
    if(event instanceof KeyEvent){
      KeyEvent key = (KeyEvent)event;
      if(key.getID()==KeyEvent.KEY_PRESSED){ //Handle key presses
        System.out.println(key.getKeyChar());
        //TODO: do something with the key press
        key.consume();
      }
    }
  }
}

相关文章