3

背景

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

尝试 1 号

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

试试 2 号

我尝试遵循本教程:http ://tips4java.wordpress.com/2008/10/10/key-bindings/ 。这是我尝试处理按空格键的操作:

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。

我的问题

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

4

2 回答 2

4

我发现我可以使用 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();
      }
    }
  }
}
于 2012-09-15T06:01:17.220 回答
4

好的,这是一个使用JPanel.

我创建了一个Frame,设置它的布局BorderLayout添加到KeyPane它,瞧...

public class KeyPane extends JPanel {

    private Timer paintTimer;
    private MouseFocusHandler mouseFocusHandler;

    private boolean spaceOn = false;
    private int yPos = 0;
    private int direction = 2;

    private Rectangle blob = new Rectangle(0, 0, 10, 10);

    public KeyPane() {

        setFocusable(true);

        InputMap im = getInputMap(WHEN_FOCUSED);
        ActionMap am = getActionMap();

        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "Space");
        am.put("Space", new SpaceAction());

        setPreferredSize(new Dimension(100, 100));

        getPaintTimer().setCoalesce(false);
        getPaintTimer().start();

    }

    @Override
    public void addNotify() {
        super.addNotify();
        requestFocusInWindow();
        addMouseListener(getMouseFocusHandler());
        getPaintTimer().start();
    }

    @Override
    public void removeNotify() {
        removeMouseListener(getMouseFocusHandler());
        getPaintTimer().stop();
        super.removeNotify();
    }

    protected Timer getPaintTimer() {
        if (paintTimer == null) {
            paintTimer = new Timer(40, new RepaintAction());
            paintTimer.setRepeats(true);
            paintTimer.setCoalesce(true);
        }
        return paintTimer;
    }

    protected MouseFocusHandler getMouseFocusHandler() {
        if (mouseFocusHandler == null) {
            mouseFocusHandler = new MouseFocusHandler();
        }
        return mouseFocusHandler;
    }

    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();

        int width = getWidth() - 1;
        int height = getHeight() - 1;

        g2d.setColor(Color.GREEN);

        blob.x = (width - blob.width) / 2;

        System.out.println(blob);
        g2d.fill(blob);

        if (spaceOn) {
            g2d.setFont(UIManager.getFont("Label.font").deriveFont(24f));
            FontMetrics fm = g2d.getFontMetrics();

            String spaceIsOn = "Space On";

            int x = (width - fm.stringWidth(spaceIsOn)) / 2;
            int y = ((height - fm.getHeight()) / 2) + fm.getAscent();

            g2d.drawString(spaceIsOn, x, y);
        }

        g2d.dispose();

    }

    protected class MouseFocusHandler extends MouseAdapter {

        @Override
        public void mouseClicked(MouseEvent e) {
            requestFocusInWindow();
        }

    }

    protected class RepaintAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            yPos += direction;
            blob.y = yPos;

            if (blob.y + blob.height > getHeight() - 1) {
                blob.y = getHeight() - 1 - blob.height;
                direction = -2;
            } else if (blob.y < 0) {
                blob.y = 0;
                direction = 2;
            }
            repaint();
        }

    }

    protected class SpaceAction extends AbstractAction {

        @Override
        public void actionPerformed(ActionEvent e) {
            spaceOn = !spaceOn;
            repaint();
        }

    }

}
于 2012-09-16T23:53:55.427 回答