带线程的java简单动画

时间:2014-03-14 00:29:40

标签: java multithreading animation runnable

我正在寻找使用线程创建一个简单的2D动画。一旦线程启动,我就无法确定在run方法中输入的内容。现在,Particle类的对象被绘制在框架上,但没有动画。此外,我可以使用您的帮助来解决当用户关闭框架时如何关闭线程

public class ParticleFieldWithThread extends JPanel implements Runnable{
private ArrayList<Particle> particle = new ArrayList<Particle>();

boolean runnable; 
public ParticleFieldWithThread (){
    this.setPreferredSize(new Dimension(500,500));


    for(int i = 0; i < 100; i++) { 
        particle.add(new Particle());
    }
    Thread t1 = new Thread();
    t1.start();




}
public void run () {
    while (true ) {
        try {
            Thread.sleep(40);
            for (Particle p : particle) {                   
                p.move();                   

            }
            repaint();

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        }


    }



   public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setColor(Color.RED);

        for (Particle p : particle) {
            g2.fill(new Rectangle2D.Double(p.getX(), p.getY(), 3, 3));
        }           

    }
   public static void main(String[] args) {
        final JFrame f = new JFrame("ParticleField");
        final ParticleFieldWithThread bb = new ParticleFieldWithThread();
        f.setLayout(new FlowLayout());
        f.add(bb);

        f.pack();
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

这是粒子类

public class Particle {
private double x , y ;

Random r = new Random();

public Particle () {

    x = r.nextDouble()*500;
    y = r.nextDouble()*500;

}
public double getX() {

    return x;
}
public double getY() {
    return y;
}
public void move() {

    x += r.nextBoolean() ? 1 : - 1;
    y += r.nextBoolean() ? 1 : - 1;
    //System.out.println("x : " + x+" y: " + y);
}



}

1 个答案:

答案 0 :(得分:4)

这没有任何用处:

Thread t1 = new Thread();
t1.start();

你需要将一个Runnable(在你的代码中,它将是类的当前对象,this)传递给Thread的构造函数,以使其具有任何含义或功能。即,

Thread t1 = new Thread(this);
t1.start();

对于我的钱,我会做一些完全不同的事情,并会使用Swing Timer进行简单的Swing动画。