0

I've got a KeyListener class called Keyboard which implements KeyListener's methods.

There are 4 states keys can have with it (UP, ISUP, DOWN, ISDOWN) all representing whether they're down, or they just became down.

Before every update to the Keyboard, I'd like to change all of the UPs to ISUPS, and DOWNs to ISDOWNs.

There is an Update method on the Keyboard class, but I don't know when to call it (because the addKeyListener() function seems to be magic and just works without having to call any functions [probably launches a thread])

How do I know when to call the Update method? (right before the Keyboard is about to fire events)

Here's the Keyboard class itself:

package game.input;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.Map;

enum KeyStatus
{
    DOWN, ISDOWN, UP, ISUP
}

public class Keyboard implements KeyListener
{
    private Map<Character, KeyStatus> keys;

    public Keyboard()
    {
        keys = new HashMap<Character, KeyStatus>();

        for (int i = 0; i < 256; i++)
        {
            keys.put((char)i, KeyStatus.ISUP);
        }
    }

    public void update() //This should be called after every event loop (how?)
    {
        for (Map.Entry<Character, KeyStatus> ks: keys.entrySet())
        {
            if (ks.getValue() == KeyStatus.UP)
                keys.put(ks.getKey(), KeyStatus.ISUP);

            else if (ks.getValue() == KeyStatus.DOWN)
                keys.put(ks.getKey(), KeyStatus.ISDOWN);
        }
    }

    public boolean keyDown(char i)
    {
        return (keys.get(i) == KeyStatus.DOWN || keys.get(i) == KeyStatus.ISDOWN);
    }

    public boolean onKeyDown(char i)
    {
        return (keys.get(i) == KeyStatus.DOWN);
    }

    public boolean keyUp(char i)
    {
        return (keys.get(i) == KeyStatus.UP || keys.get(i) == KeyStatus.ISUP);
    }

    public boolean onKeyUp(char i)
    {
        return (keys.get(i) == KeyStatus.UP);
    }


    @Override
    public void keyPressed(KeyEvent key)
    {
        keys.put(key.getKeyChar(), KeyStatus.DOWN);
    }

    @Override
    public void keyReleased(KeyEvent key)
    {
        keys.put(key.getKeyChar(), KeyStatus.UP);
    }

    @Override
    public void keyTyped(KeyEvent key)
    {
    }

}
4

1 回答 1

2

KeyListener注册到一个组件中,EventQueue当某种 aKeyEvent发生时,它会被通知。由EventQueue直接绑定到操作系统/本地层的平台特定机制通知。

当涉及到侦听器时,Swing 通常使用观察者模式。也就是说,您将一个侦听器附加到一个组件,该组件会在发生某些事情时告诉您

您不应该“需要”调用任何方法来检查键的状态。相反,当KeyEvent触发 a 时,将通知(通过事件链)并通过接口KeyListener触发适当的事件。KeyListener

AKeyListener需要注册到某个在屏幕上可见的组件,可以获得键盘焦点,并且在事件发生时具有焦点。

查看如何编写关键侦听器以获取更多详细信息。

您可能还会发现事件侦听器简介很有用。

KeyListener遭受焦点问题(只有当前可聚焦/聚焦的组件可以接收KeyEvents)。建议您改用Key Bindings

更新

经过一轮循环的讨论,我们弄清楚真正的问题是什么,我们得出结论,OP 正在尝试生成当前按下但已由游戏引擎处理的键的掩码列表,以消除键重复触发更多更新。

我们得出的结论是,OP 应该生成一个“已处理”和“活动”的密钥列表。

当按键按下事件被触发时,键盘处理程序将检查该键是否存在于“已处理”列表中,如果存在,则忽略该键,否则将其放置在活动列表中。

当游戏引擎处理键时,它会扫描“活动”列表,采取行动并将每个键放在“已处理”列表中。

一旦密钥被释放,它就会从已处理列表中删除。

于 2013-05-07T23:44:23.467 回答