2
我正在寻找使用线程创建简单的2D动画。一旦线程启动,我无法确切知道要在运行方法中放置什么。现在,Particle类的对象被绘制在框架上,但没有动画。此外,我可以和如何当用户关闭框架带线程的java简单动画
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);
}
}
如果你打算使用连续动画,最好使用[主动渲染](http://docs.oracle.com/javase/tutorial/extra/fullscreen/rendering.html) – vandale
我很想知道Swing'Timer'有什么问题?这引入了在更新粒子的同时绘制UI的风险...... – MadProgrammer
Swing计时器没有什么错,这是一个家庭作业问题。这个问题让我们用线程而不是定时器来做动画 – user3363135