-
Moving Box
Hiya, I wrote a program that you move a box around using arrow keys. I figured how to move the box according to two keys pressed simultaneously like right and up. Here's the code:
Code:
public void keyReleased(KeyEvent evt){
int rel = evt.getKeyCode();
if(rel == KeyEvent.VK_UP) {
isUp = false;
}
if(rel == KeyEvent.VK_DOWN) {
isDown = false;
}
if(rel == KeyEvent.VK_LEFT) {
isLeft = false;
}
if(rel == KeyEvent.VK_RIGHT) {
isRight = false;
}
}
Code:
public void keyPressed(KeyEvent evt) {
key = evt.getKeyCode();
if(key == KeyEvent.VK_LEFT) {
if(isUp) {
squareY -= 5;
if(squareY<3) squareY = 3;
}
if(isDown) {
squareY += 5;
if(squareY>getHeight()-43) squareY = getHeight() -43;
}
squareX -= 5;
if(squareX<3) squareX = 3;
isLeft = true;
repaint();
}
if(key == KeyEvent.VK_RIGHT) {
if(isUp) {
squareY -= 5;
if(squareY<3) squareY = 3;
}
if(isDown) {
squareY += 5;
if(squareY>getHeight()-43) squareY = getHeight() -43;
}
squareX += 5;
if(squareX>getWidth()-43) squareX = getWidth()-43;
isRight = true;
repaint();
}
if(key == KeyEvent.VK_UP) {
if(isRight) {
squareX += 5;
if(squareX>getWidth()-43) squareX = getWidth()-43;
}
if(isLeft) {
squareX -= 5;
if(squareX<3) squareX = 3;
}
squareY -= 5;
if(squareY<3) squareY = 3;
isUp = true;
repaint();
}
if(key == KeyEvent.VK_DOWN) {
if(isRight) {
squareX += 5;
if(squareX>getWidth()-43) squareX = getWidth()-43;
}
if(isLeft) {
squareX -= 5;
if(squareX<3) squareX = 3;
}
squareY += 5;
if(squareY>getHeight()-43) squareY = getHeight() -43;
isDown = true;
repaint();
}
}
The problem is, for example: when I press UP + RIGHT, it goes that way ok cool, but when i release RIGHT, the box stops. I want it to keep going (to up in this case). Thank you :)
-
instead of handling the update position state on keyboard event, you could just record the event and have a seperate update thread that does the processing.
In other words, when keyboard happens then set a flag for up/down and left/right and have a thread that checks ever 50ms or so to update the position.
Code:
//inner class
private classs updateThread extends Thread
{
public void run()
{
try
{
sleep(50); //sleep 50 ms
...
//update pos on flags
}
catch(Exception e) { ... }
}
}
-
I'm not familiar with threads, but I'll check some tutorials for it. Thank you.