java repaint()和初始化对象

时间:2011-10-02 20:05:51

标签: java object animation paint instantiation

我有一个类应该使用paintComponent和repaint()模拟一个firework动画我检测到的问题是“Firework”是新初始化的 每次调用该方法时,每次都会将firework的projectileTime字段重置为零(在构造函数中指定)。实例化烟花对象的适当位置在哪里,以便projectileTime字段适当增加? (在本课程或其他课程中) 见代码:

public class FireworkComponent extends JComponent {

private static final long serialVersionUID = 6733926341300224321L;
private double time;

public FireworkComponent(){
time=0;
}
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    g.translate(0, this.getHeight());

    Firework f= new Firework(this.getWidth()/2,0,73,90,Color.red,5);
    f.addFirework(75,35,Color.BLUE,6);
    f.addFirework(75, 155, Color.green, 6);

    time+=.1;

    Point point=f.addTime(.1);
    g.fillOval(point.x, (-point.y),15,15);

    try{
        Thread.sleep(500);
        System.out.println("sleep");
    }
    catch (InterruptedException e){
        e.printStackTrace();
    }

    this.repaint();
}
}

3 个答案:

答案 0 :(得分:2)

首先从paintComponent()方法中删除Thread.sleep()。

然后,您需要定义随时间变化的Firework组件的属性。

最后,您将使用Swing Timer来安排烟花的动画。每次Timer触发时,您都会更新组件属性,然后在组件上调用repaint()。

答案 1 :(得分:2)

  • 不要在Paint Graphics2D中添加Firework f= new Firework(this.getWidth()/2,0,73,90,Color.red,5);,你必须在此之前做好准备

  • 请勿使用Thread.sleep(int);延迟绘画,因为Graphics2D有javax.swing.Timer,但您必须使用Timer初始化paintComponent(),而不是停留在绘图内画体

  • 不确定是否以某种方式工作Point point=f.addTime(.1);

修改

动画的

example

答案 2 :(得分:2)

Firework存储为类级别属性,并在FireworkComponent构造函数中对其进行实例化。

相关问题