R.Namakin
R.Namakin

Reputation: 1

Setting up a timer for game

I want to make a fruit basket game. The idea here is that I want to draw fruits from the top of screen to bottom and I also want to do that with timer.I tried several ways but I got no result. Here is what I did but it's totally doing wrong.

 Timer timer = new Timer();
 while (getY() != 1500) {
        timer.schedule(new DrawFruit(frame, g, x) {
            @Override
            public void run() {

                g.drawImage(Toolkit.getDefaultToolkit().getImage(Panel.class.getResource(Consts.ImageResource.APRICOT_DIR)), 500, getY(), frame);
                frame.repaint();
                setY(getY() + 30);

            }
        }, 0, 1000);
    }

and the DrawFruit Class

abstract class DrawFruit extends TimerTask {
private JFrame jFrame;
private Graphics g;
private int x;

public JFrame getJFrame() {
    return jFrame;
}

public void setJFrame(JFrame jFrame) {
    this.jFrame = jFrame;
}

public Graphics getG() {
    return g;
}

public void setG(Graphics g) {
    this.g = g;
}

public int getX() {
    return x;
}

public void setX(int x) {
    this.x = x;
}

public DrawFruit(JFrame frame , Graphics g , int x){
    setJFrame(frame);
    setG(g);
    setX(x);
}


@Override
public void run() {

}

}

Upvotes: 0

Views: 51

Answers (1)

camickr
camickr

Reputation: 324118

You should NOT be using looping code. The point of a Timer is that it replaces the loop. All a Timer does is generate an event at your specified time interval. So when the event is generated you just adjust the "Y" value and repaint the component.

However, you should not be using a TimerTask for this.

Swing components should be updated on the Event Dispatch Thread (EDT). Therefore you should be using a Swing Timer. Read the tutorial for a working example to get you started.

Upvotes: 1

Related Questions