Java - Picture doesn't show until end of loop?
In Java, I have successfully d开发者_如何学Cisplayed 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?
In addition to other suggestions:
Never read the image in the painting method. Read the image when you construct the class or pass in the image with a setImage(...) method.
Custom painting is done by overriding the paintComponent() method, not the paint() method.
Use a Timer
for this, and get rid of the Thread.sleep()
. You're running this code on the UI thread, and when you call Thread.sleep()
you're putting the UI thread to sleep, which means no updating until the entire loop is complete.
精彩评论