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) {
            public void run() {

                g.drawImage(Toolkit.getDefaultToolkit().getImage(Panel.class.getResource(Consts.ImageResource.APRICOT_DIR)), 500, getY(), frame);
                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){

public void run() {



1 answer

  • answered 2017-06-17 19:54 camickr

    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.