I am trying to create a walking animation. It should alternate between playerLeft and playerLeftWalk. The code is shown below:
public class MyClass extends JPanel implements ActionListener, KeyListener{
protected Timer tm = new Timer(10, this);
protected Clip clip;
protected Image background, playerSprite, playerLeft, playerLeftWalk;
protected int mapdx = 0;
protected int mapdy = 0;
protected int mapX = 0;
protected int mapY = 0;
protected int playerX = 1060;
protected int playerY = 2800;
protected volatile boolean activeThread;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(this.background, this.mapX + this.mapdx, this.mapY - this.mapdy, this);
g.drawImage(this.playerSprite, this.playerX, this.playerY, this);
}
@Override
public void actionPerformed(ActionEvent e) {
mapX += mapdx;
mapY += mapdy;
this.repaint();
}
@Override
public void keyPressed(KeyEvent e) {
int k = e.getKeyCode();
Thread playerControl=null;
if (!activeThread) {
this.activeThread=true;
playerControl = new Thread(new Runnable() {
@Override
public void run() {
switch (k) {
case KeyEvent.VK_LEFT:
mapdx = 1;
mapdy = 0;
System.out.println("Map X: " + mapX + " Map Y: " + mapY);
try {
playerSprite = playerLeftWalk;
Thread.sleep(250);
playerSprite = playerLeft;
} catch (InterruptedException e) {
}
break;
default:
break;
}
}
});
activeThread=false;
}
if(playerControl!=null)
playerControl.start();
}
@Override
public void keyReleased(KeyEvent e) {
int k = e.getKeyCode();
if(k == KeyEvent.VK_LEFT) {
mapdx = 0;
mapdy = 0;
playerSprite = playerLeft;
}
}
@Override
public void keyTyped(KeyEvent e) {
}
}
What the code above does is work for the first "cycle" and then stutter thereafter. I assume that what is happening is that multiple threads are being created, making the image stutter.