In Java, I have successfully displayed an image on the screen. Now I want to make it move by running it through a for loop. The for loop runs 10 times and sleeps for 1 second each time. Instead of moving the image every second as expected, I have to wait 10 seconds, then 10 images show up.
Here’s my code:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class ImageDraw extends JComponent {
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Image img1 = Toolkit.getDefaultToolkit().getImage("player.png");
int x = 0;
int y = 0;
for(int i = 0;i<10;i++){
try {
Thread.sleep(1000);
x+=10;
y+=10;
g2.drawImage(img1, x, y, this);
repaint();
} catch (InterruptedException e) {
e.printStackTrace();
System.exit(0);
}
} //end for
} //end paint
} //end class
How would I make it so the image looks as if it’s moving everytime it runs through the loop?
Use a
Timerfor this, and get rid of theThread.sleep(). You’re running this code on the UI thread, and when you callThread.sleep()you’re putting the UI thread to sleep, which means no updating until the entire loop is complete.