Question

could use your help homework involving swing timers, action listeners and multiple objects. I don't know if posting the question is allowed here but i'm having trouble with the animation, here's what i have so far

Create a class Particle that has two double fields x and y, a constructor that initializes these fields to random values between 0 and 500, methods getX and getY that return their values, and a method void move() that randomly adds or subtracts one to each of the values of x and y. (The quantities added to x and y are two separate random numbers.) Next, create a class ParticleFieldWithTimer that extends JPanel. This class should prefer to be 500 * 500 pixels in size. Its constructor should first fill an ArrayList field with 100 Particle objects, then start a Swing Timer that ticks 25 times a second. At each tick, the action listener should first call the method move for each particle, and then call repaint. The paintComponent method of ParticleFieldWithTimer should draw each particle as a 3*3 rectangle to its current coordinates. Make sure that the Timer will stop when the user closes the frame

This is the ParticleFieldWithTimer class

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;


public class ParticleFieldWithTimer extends JPanel{
    private ArrayList<Particle> particle = new ArrayList<Particle>();
    Timer timer; 
    boolean b; 
    public ParticleFieldWithTimer (){
        this.setPreferredSize(new Dimension(500,500));


    for(int i = 0; i < 100; i++) { 
        particle.add(new Particle());
        timer = new Timer(40, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                // change polygon data
                // ...
                Particle p = new Particle();
                p.move();
                repaint();

            }
        });


    }





}
   public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        for (Particle p: particle) {

        double temp1 = p.getX();
        double temp2 = p.getX();
        int tempX = (int) temp1;
        int tempY = (int) temp2;
        g2.fillRect(tempX, tempY, 3, 3);
        }




    }
   public static void main(String[] args) {
        final JFrame f = new JFrame("ParticleField");
        final ParticleFieldWithTimer bb = new ParticleFieldWithTimer();
        f.setLayout(new FlowLayout());
        f.add(bb);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                try {
                    bb.finalize();
                } catch (Throwable e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                f.dispose();
            }
        });
        f.pack();
        f.setVisible(true);
    }
}

This is the particle class

import java.util.Random;


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.nextInt(2) - 1;
    y = r.nextInt(2) - 1;
    System.out.println(x + "  " + y);
}

}

Was it helpful?

Solution

This...

for(int i = 0; i < 100; i++) { 
    particle.add(new Particle());
    timer = new Timer(40, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            // change polygon data
            // ...
            Particle p = new Particle();
            p.move();
            repaint();

        }
    });
}

Is the wrong approach, it is create a 100 Timers, which will affect the performance of your system.

You are also creating a new Particle each time the timer ticks, which isn't what you really want to do either, you want to affect the Particles you've already created...

Instead, create your particles...

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

Then create your Timer and within it, iterate through the particles you've already created...

timer = new Timer(40, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        for (Particle p : particle) {
            p.move();
        }
        repaint();
    }
});

Don't forget to start the timer...

timer.start();

Or change the color of the Graphics context, which is probably still set to the background of the panel...

Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
for (Particle p : particle) {

I also noted that...

x = r.nextInt(2) - 1;
y = r.nextInt(2) - 1;

Isn't doing what you want. It will always make the values between -1 and 1. Instead, you want to add the result to the x/y values...

x += r.nextInt(2) - 1;
y += r.nextInt(2) - 1;

Now, this kind of made the values "drag" across the screen in a (mostly) uniform manner...

You could try using...

x += r.nextBoolean() ? 1 : - 1;
y += r.nextBoolean() ? 1 : - 1;

But this ended up making them dance around in place (mostly)...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top