简体   繁体   English

使用箭头键移动JLabel

[英]Moving JLabel with arrow keys

Sorry, for double posting, already posted this question once, but I realized I weren't explicit enough. 抱歉,对于双重发布,已经发布了此问题一次,但是我意识到我不够明确。 I still haven't managed to find an answer to my question so I'll try to better describe my problem here: 我仍然没有找到问题的答案,因此我将尝试在这里更好地描述我的问题:

I have the following classes: 我有以下课程:

public class Paddle extends JLabel {}
public class Canvas extends JPanel implements Runnable {}

Now, when I start the thread described in Canvas, I want an infinite loop (loops while program is exited). 现在,当我启动Canvas中描述的线程时,我想要一个无限循环(退出程序时循环)。 In this loop I've got a DIRECTION variable. 在此循环中,我有一个DIRECTION变量。 When the left arrowkey is pressed I'd like this to be set -1. 当按下左箭头键时,我希望将其设置为-1。 If right arrow key is pressed I'd like +1 to be it's value. 如果按下向右箭头键,则我希望+1是它的值。 If neither of the above cases is true, it's value should default 0. 如果以上两种情况都不成立,则其值应默认为0。

I hope I was more explicit this time. 我希望这次我更加明确。 If not please tell. 如果没有,请告诉。

Well, to get the keystrokes you need to have a class that implements KeyListener 好吧,要获取按键,您需要具有一个实现KeyListener的类

Like this: 像这样:

public class MyKeyListener implements KeyListener, MouseListener{
   int direction = 0;

    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode()  == KeyEvent.VK_LEFT) direction = -1;
        else if(e.getKeyCode()  == KeyEvent.VK_RIGHT) direction = 1;
    }

    public void keyReleased(KeyEvent e) {
        direction = 0;
    }
}

Then in your initialization code (for example, in the constructor of your JPanel derived class) you set the key listener to an instance of your MyKeyListener class 然后,在初始化代码中(例如,在JPanel派生类的构造函数中),将键侦听器设置为MyKeyListener类的实例。

   MyKeyListener  mk = new MyKeyListener();
   this.addKeyListener(mk);

In your loop, you just look at the direction feild of mk; 在循环中,您只需查看mk的方向即可;

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

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