سؤال

I'm looking to create a simple 2D animation using a thread. Once the thread is launched, i'm having trouble figuring out exactly what to put in the run method. Right now, the objects of the Particle class are painted on the frame but there's no animation. Also i could use your help with how to close the thread when the user closes the frame

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);
    }
}

Here's the particle class

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);
}



}
هل كانت مفيدة؟

المحلول

This does nothing of use:

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

You need to pass a Runnable (in your code, it would be the current object of the class, the this) into the Thread's constructor for it to have any meaning or function. i.e.,

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

For my money, I'd do something completely different and would use a Swing Timer for simple Swing animation.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top