改善我的键盘输入(KeyListener)Java

时间:2018-07-26 14:56:32

标签: java swing events awt keylistener

问题出在空循环运行的轮询方法中。 另外,要添加Windows按钮,我必须将数组增加到524。

keys = new boolean [524]; polled = new int [524];

我想摆脱这种循环,但是我还没有弄清楚该怎么做。

如何删除轮询循环以解决添加大量按钮的问题?

class KeyBoardInput implements KeyListener
{
    private final boolean[] keys;
    private final int[] polled;

    KeyBoardInput()
    {
        keys = new boolean[256];
        polled = new int[256];
    }

    public boolean keyDownOnce(int keyCode)
    {
        return polled[keyCode] == 1;
    }

    public void poll()
    {
        for(int i = 0; i < keys.length; i++) // <-this
        {
            if(keys[i]) 
            {
                polled[i]++;
            } 
            else 
            {
                polled[i] = 0;
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e)
    {

    }

    @Override
    public void keyPressed(KeyEvent e)
    {
        int keyCode = e.getKeyCode();
        if( keyCode >= 0 && keyCode < keys.length ) 
        {
            keys[ keyCode ] = true;
        }
    }

    @Override
    public void keyReleased(KeyEvent e)
    {
        int keyCode = e.getKeyCode();
        if( keyCode >= 0 && keyCode < keys.length ) 
        {
            keys[ keyCode ] = false;
        }
    }

}

调用KeyBoardInput的类。

@Override
public void run()
{
    running = true;
    while(running)
    {
        gameLoop();
    }
}

private void gameLoop()
{
    processInput();
}

private void processInput()
{
    keyboard.poll();

    if(keyboard.keyDownOnce(KeyEvent.VK_SPACE)) 
    {
        System.out.println("VK_SPACE");
    }
    if(keyboard.keyDownOnce(KeyEvent.VK_C)) 
    {
        System.out.println("VK_C");
    }
    if(keyboard.keyDownOnce(KeyEvent.VK_ALT)) 
    {
        System.out.println("VK_ALT");
    }
}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,原来有可能。

@Override
    public synchronized void keyPressed(KeyEvent e)
    {
        if (e.getKeyCode() == KeyEvent.VK_SPACE)
        {
            System.out.println("VK_SPACE");
        }
        if (e.getKeyCode() == KeyEvent.VK_C)
        {
            System.out.println("VK_C");
        }
    }