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 Timer
s, 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 Particle
s 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)...