开发者

java repaint() and initializing objects

开发者 https://www.devze.com 2023-04-10 07:31 出处:网络
I have a class that is su开发者_如何学运维pposed to simulate a firework animation using paintComponent and repaint() the problem that I have detected is that a \"Firework\" is newly initialized

I have a class that is su开发者_如何学运维pposed to simulate a firework animation using paintComponent and repaint() the problem that I have detected is that a "Firework" is newly initialized each time the method is invoked so the projectileTime field of the firework is reset to zero (as specified in the constructor) each time. Where is the appropriate place to instantiate a firework object so that the projectileTime field is incremented appropriately? (In this class or in another class) see code:

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();
}
}


First of all get rid of the Thread.sleep() from the paintComponent() method.

Then you need to define properties of the Firework component that change over time.

Finally, you would use a Swing Timer to schedule the animation of the fireworks. Every time the Timer fires you would update the component properties and then invoke repaint() on the component.


Store the Firework as a class level attribute and instantiate it in the FireworkComponent constructor.


please

  • don't add Firework f= new Firework(this.getWidth()/2,0,73,90,Color.red,5); inside Paint Graphics2D, you have to prepare this before

  • don't delay you paint by using Thread.sleep(int);, for Graphics2D is there javax.swing.Timer, but you have to initialize paintComponent() by using Timer, not stop to painting inside the Paint body

  • not sure if somehow working Point point=f.addTime(.1);

EDIT

for animations is there example

0

精彩评论

暂无评论...
验证码 换一张
取 消