用箭头键移动 JLabel [英] Moving JLabel with arrow keys

查看:45
本文介绍了用箭头键移动 JLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

抱歉,对于双重发布,这个问题已经发布过一次,但我意识到我不够明确.我仍然没有设法找到我的问题的答案,所以我会尽量在这里更好地描述我的问题:

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:

我有以下课程:

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

现在,当我启动 Canvas 中描述的线程时,我想要一个无限循环(程序退出时的循环).在这个循环中,我有一个 DIRECTION 变量.当按下左箭头键时,我希望将其设置为 -1.如果按下右箭头键,我希望 +1 成为它的值.如果以上两种情况都不成立,则其值应默认为 0.

Now, when I start the thread described in Canvas, I want an infinite loop (loops while program is exited). In this loop I've got a DIRECTION variable. When the left arrowkey is pressed I'd like this to be set -1. If right arrow key is pressed I'd like +1 to be it's value. If neither of the above cases is true, it's value should default 0.

我希望这次我更直白.如果没有请告诉.

I hope I was more explicit this time. If not please tell.

推荐答案

好吧,要获得按键,您需要有一个实现 KeyListener

Well, to get the keystrokes you need to have a class that implements KeyListener

像这样:

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;
    }
}

然后在您的初始化代码中(例如,在您的 JPanel 派生类的构造函数中)您将键侦听器设置为 MyKeyListener 类的实例

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

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

在您的循环中,您只需查看 mk 的方向字段;

In your loop, you just look at the direction feild of mk;

这篇关于用箭头键移动 JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆