简体   繁体   English

Java-图片直到循环结束才显示?

[英]Java - Picture doesn't show until end of loop?

In Java, I have successfully displayed an image on the screen. 在Java中,我已经成功在屏幕上显示了图像。 Now I want to make it move by running it through a for loop. 现在,我想通过运行一个for循环使其移动。 The for loop runs 10 times and sleeps for 1 second each time. for循环运行10次,每次睡眠1秒。 Instead of moving the image every second as expected, I have to wait 10 seconds, then 10 images show up. 不必按预期的每秒移动图像,而是必须等待10秒钟,然后显示10张图像。

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: 除了其他建议:

  1. 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. 构造类时读取图像,或使用setImage(...)方法传递图像。

  2. Custom painting is done by overriding the paintComponent() method, not the paint() method. 通过覆盖paintComponent()方法而不是paint()方法来完成自定义绘制。

Use a Timer for this, and get rid of the Thread.sleep() . 为此使用Timer ,并摆脱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. 您正在UI线程上运行此代码,并在调用Thread.sleep()时将UI线程置于睡眠状态,这意味着在整个循环完成之前不会进行任何更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM