im learning Java2d, and im trying to animate my image in x coordinate using a Timer, but is not working, the idea is between a time frame the image x value increments a value making it to move, can someone figure out what is the problem in my code?
Here is the code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class Screen extends JPanel {
int posX;
Timer timer;
private BufferedImage image;
public Screen() {
setDoubleBuffered(true);
posX = 1;
timer = new Timer();
timer.scheduleAtFixedRate(new Anima(), 100, 10);
//Smile Icon
try{
image = ImageIO.read(getClass().getResource("/smily.png"));
}catch(IOException e){
e.printStackTrace();
}
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(image,this.posX,100,null);
}
class Anima extends TimerTask{
public void run() {
posX += 20;
repaint();
}
}
public void incMove() {
posX += 20;
}
}
Your code is working, but you are updating too fast.
Try
To check your animation.