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). 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.
Well, to get the keystrokes you need to have a class that implements 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
MyKeyListener mk = new MyKeyListener();
this.addKeyListener(mk);
In your loop, you just look at the direction feild of mk;
精彩评论