首页 > 解决方案 > 图像数组创建动画

问题描述

我正在尝试创建动画。两个图像应该移动 - 汽车和人类。但是人类由两个图像组成,因此它看起来像是一个适当的运动。我正在尝试将图像数组放入我的代码中,但它不起作用。你能帮忙吗?这是我的代码

public class Main extends JFrame implements Runnable{
int x=0;

public Image car = new ImageIcon( "car.png").getImage();
public Image[] human;
private Thread thread;

public Main() {
    super("Animation");
    this.setSize(700,500);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    thread = new Thread(this);
    thread.start();
}

public void paint(Graphics g) {
    g.setColor(Color.white);
    g.fillRect(0,0,this.getWidth(),this.getHeight());//background

    g.drawImage(car,x,150,null);

    human = new Image[2];
    human[0] = new ImageIcon("move.png").getImage();
    human[1] = new ImageIcon("stop.png").getImage();

    for (int i=0; i<2; i++)
    {
        g.drawImage(human[i], x , 200,null);
    }

}

public static void main(String[] args) {
    Main f = new Main();
    f.setVisible(true);
    f.setLocationRelativeTo(null);      
}

@Override
public void run() {
    while(true)
    {
        x++; 

        repaint();
        try {
            Thread.sleep(100);
        }catch(InterruptedException e) {
            System.out.println("Error!");
        }
    }
}

}

标签: javaanimationimageicon

解决方案


推荐阅读