Java Swing Key Handler偶尔无法正常工作

时间:2016-02-17 16:02:07

标签: java swing key-bindings

我正在开发基于Java Swing的视频游戏。我在检测击键时遇到问题 - “A”(向左移动)和“D”键(向右移动),几乎看起来它们没有发射(但很少发生)。几乎就好像他们已经没有注册。现在,我已经设置了日志文件来捕获键盘事件,并且某些点上的一个keyHandler不会触发。现在当发生这种情况时,如果我用鼠标点击游戏的主屏幕,那么以某种方式迷路的keyHandler似乎再次起作用。几乎就好像“焦点”无意中被转移到游戏中的其他小部件一样。

以下是设置动作地图的代码:

    topStatusPanel.getInputMap().put(KeyStroke.getKeyStroke("pressed A"),
            "aCharKeyPressed");
    topStatusPanel.getActionMap().put("aCharKeyPressed", aKeyActionPressed);


    topStatusPanel.getInputMap().put(KeyStroke.getKeyStroke("released A"), 
            "aCharKeyReleased");
    topStatusPanel.getActionMap().put("aCharKeyReleased", aKeyActionReleased);



    topStatusPanel.getInputMap().put(KeyStroke.getKeyStroke("pressed D"), 
            "dCharKeyPressed");
    topStatusPanel.getActionMap().put("dCharKeyPressed", dKeyActionPressed);

    topStatusPanel.getInputMap().put(KeyStroke.getKeyStroke("released D"), 
            "dCharKeyReleased");
    topStatusPanel.getActionMap().put("dCharKeyReleased", dKeyActionReleased);

    MoveSubLeftActionStart aKeyActionPressed= new MoveSubLeftActionStart();
    MoveSubLeftActionStop aKeyActionReleased= new MoveSubLeftActionStop();
    MoveSubRightActionStart dKeyActionPressed= newMoveSubRightActionStart();
    MoveSubRightActionStop dKeyActionReleased= new MoveSubRightActionStop();

真的很感激任何想法。有没有办法强调焦点到特定的小部件? - 然后我会为游戏中的每个其他小部件设置它“不可聚焦吗?”这可能是问题吗?感谢这里的任何帮助。

1 个答案:

答案 0 :(得分:0)

这是对焦点管理和键盘事件处理的深入处理。 如果您的JPanel包含其他组件,它们可能会获得焦点而不会在组件链中传播关键事件。

http://docs.oracle.com/javase/6/docs/api/java/awt/doc-files/FocusSpec.html#RequestingFocus