简体   繁体   English

Java Swing密钥处理程序偶尔不起作用

[英]Java Swing Key Handlers sporadically not working

I am developing a Java Swing based video game. 我正在开发基于Java Swing的视频游戏。 I am having a problem with detecting keystrokes- the 'A' (move left) and 'D' keys (move right), where it almost seems they are not firing (but happens rarely). 我在检测击键时遇到问题-“ A”键(向左移动)和“ D”键(向右移动),几乎似乎它们没有触发(但很少发生)。 Almost as if they have become unregistered. 几乎就像它们已取消注册一样。 Now, I have setup log files to capture the keyboard events, and again one of the keyHandlers at some point does not fire. 现在,我有了设置日志文件来捕获键盘事件,并且在某个时刻再次无法触发其中一个keyHandlers。 Now when this does happen, if I click into the main screen of the game with my mouse, the keyHandler that somehow got lost seems to work again. 现在,当发生这种情况时, 如果我用鼠标单击游戏的主屏幕 ,那么似乎迷路的keyHandler似乎又可以工作了。 Almost as if the "Focus" was inadvertantly transferred to some other widget in the game. 几乎就像“焦点”被无意间转移到了游戏中的其他小部件一样。

Here is the code to setup the Action Maps: 以下是设置操作图的代码:

    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();

Would really appreciate any ideas on this. 真的很感谢任何想法。 Is there a way to force focus to a specific widget?- would I then for every other widget in the game have to set it to "unfocusable?" 有没有一种方法可以将焦点强制到特定的小部件?-那么我是否需要为游戏中的其他所有小部件将其设置为“无法对焦”? Could this be the issue? 这可能是问题吗? Appreciate any help here. 在这里感谢任何帮助。

Here's an in-depth treatment on focus management and keyboard event handling. 这是对焦点管理和键盘事件处理的深入处理。 If your JPanel contains other components, they might get the focus and not propagate the key events up the component chain. 如果您的JPanel包含其他组件,它们可能会成为焦点,并且不会在组件链中传播关键事件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM