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