I'm trying to make a program in java that involves making an object move constantly from a single key press. Think Pacman, where you press up once and Pacman continues to go up until you press another key. I want to keep the code simple if possible. My original movement (one keypress = one movement) is like this:
public class AL extends KeyAdapter {
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == e.VK_A){
x -= 5;
}
if(keyCode == e.VK_D){
x += 5;
}
if(keyCode == e.VK_W){
y -= 5;
}
if(keyCode == e.VK_S){
y += 5;
}
}
The x and y in values are the position of an oval. This works perfectly, but I want it to keep moving after I press the key only once, instead of having to hold it to keep the movement going. I tried a while loop with a boolean parameter that moves while true and doesn't while false, but as soon as I activate the loop, it freezes the program. Here's an example of that bit of code:
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == e.VK_LEFT && moveL==false){
moveL=true;
moveR=false;
moveU=false;
moveD=false;
while(moveL){
x--;
}
}
Please help me figure this out, I've been trying and looking around for days now. I appreciate any help you guys can give. Thanks.
The basic concept revolves around this idea of a "delta" or "change" value. This value is then applied to the state you want to change by either incrementing or decrementing the state value by it.
Because of the nature of Swing, you can't block the Event Dispatching Thread, otherwise you end up preventing from processing incoming events (such as paint and key events).
Equally, you should never try and update any UI component (or state variable that might effect the UI) from any thread other then the EDT.
While there are tricks you can apply to facilitate these requirements, the simplest is to use a
javax.swing.Timer
, which triggers aactionPerformed
event on a regular bases within the EDT.When this occurs you "update" all the elements by the prescribed amount and repaint the screen.
I would also recommend that you take the time to learn about Key Bindings,
KeyListener
suffer from focus issues, which key bindings are capable of addressing...You need to process the move in a separate thread. I.e.:
Then you keep a reference to an instance of Pacman class in your Gui class and respond to various key presses by changing pacman's parameters: