a question about keyPressed and keyReleased
hi
I used this code to move an image over the display:
import javax.microedition.lcdui.*;
public class Displayable1 extends Canvas implements CommandListener {
private Image image;
private int x = 50;
private int y = 50;
private int speed = 5;
Command exit;
public Displayable1() {
try {
image = Image.createImage("/pressRelease/space1on.png");
}
catch (Exception e) {}
exit = new Command("Exit", Command.EXIT, 1);
addCommand(exit);
setCommandListener(this);
}
protected void paint(Graphics g) {
int anchor = Graphics.LEFT | Graphics.TOP;
g.drawImage(image, x, y, anchor);
}
private void moveImage(int direction) {
switch (direction) {
case 1: x+=speed;
break;
case 2: y+=speed;
break;
case 3: x-=speed;
break;
case 4: y-=speed;
break;
}
repaint();
}
public void commandAction(Command command, Displayable displayable) {
}
protected void keyPressed(int keyCode) {
int action = getGameAction(keyCode);
switch (action) {
case Canvas.RIGHT:
moveImage(1);
break;
case Canvas.LEFT:
moveImage(3);
break;
case Canvas.UP:
moveImage(4);
break;
case Canvas.DOWN:
moveImage(2);
break;
}
}
}
how can I add the keyReleased method?
what I need is this: a key is pressed, the image moves and still moving until the key is released.
so first keyPressed, then movement starts, and then when the keyReleased condition is true stops.
can you help me with a code sample?
thank you!
eml
previous answer is correct...
You should use thread anyway, not only for getting the keyRelease event, if you want a smooth animation.
The key latching behavior that you want could be implemented using one int mask (using bitwise operations) instead of four booleans, but that's not that important.
by the way, the behavior you need is part of the MIDP 2.0 spec
It's in GameCanvas: suppressKeyEvents.