如何检查按下的键是否是 Java KeyListener 中的箭头键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/616924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:01:16  来源:igfitidea点击:

How to check if the key pressed was an arrow key in Java KeyListener?

javaevents

提问by Click Upvote

Can you help me refactor this code:

你能帮我重构这段代码吗:

public void keyPressed(KeyEvent e)
    {

    if (e.getKeyCode()==39)
    {
                //Right arrow key code
    }

    else if (e.getKeyCode()==37)
    {
                //Left arrow key code
    }

    repaint();

}

Please mention how to check for up/down arrow keys as well.Thanks!

请提及如何检查向上/向下箭头键。谢谢!

采纳答案by OscarRyz

public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    switch( keyCode ) { 
        case KeyEvent.VK_UP:
            // handle up 
            break;
        case KeyEvent.VK_DOWN:
            // handle down 
            break;
        case KeyEvent.VK_LEFT:
            // handle left
            break;
        case KeyEvent.VK_RIGHT :
            // handle right
            break;
     }
} 

回答by Pooria

If you mean that you wanna attach this to your panel (Window that you are working with).

如果您的意思是要将其附加到您的面板(您正在使用的窗口)。

then you have to create an inner class that extend from IKeyListener interface and then add that method in to the class.

那么你必须创建一个从 IKeyListener 接口扩展的内部类,然后将该方法添加到类中。

Then, attach that class to you panel by: this.addKeyListener(new subclass());

然后,通过以下方式将该类附加到您的面板: this.addKeyListener(new subclass());

回答by TofuBeer

You should be using things like: KeyEvent.VK_UP instead of the actual code.

你应该使用类似的东西: KeyEvent.VK_UP 而不是实际的代码。

How are you wanting to refactor it? What is the goal of the refactoring?

你想如何重构它?重构的目标是什么?

回答by banjollity

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_RIGHT ) {
            //Right arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_LEFT ) {
            //Left arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_UP ) {
            //Up arrow key code
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN ) {
            //Down arrow key code
    }

    repaint();
}

The KeyEvent codes are all a part of the API: http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

KeyEvent 代码都是 API 的一部分:http: //docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html

回答by Jaime

Just to complete the answer (using the KeyEvent is the way to go) but up arrow is 38 and down arrow is 40 so:

只是为了完成答案(使用 KeyEvent 是要走的路)但是向上箭头是 38,向下箭头是 40 所以:

    else if (e.getKeyCode()==38)
    {
            //Up arrow key code
    }
    else if (e.getKeyCode()==40)
    {
            //down arrow key code
    }