0

I am trying to set a timer class to control when the ball chooses a new color. I need to make the ball change colors at a set time and not just continuously set different colors. This is my ball class and the whole program is run through a start class.

public void go() {
    if (dx >= 0) {
        dx = 20;
    }
}

public void update(Start sp) {
    if (x + dx > sp.getWidth() - radius * 2) {
        x = sp.getWidth() - radius * 2;
        dx = -dx;
    }
    else if (x + dx < 0) {
        dx = -dx;
    }
    else {
        x += dx;
    }
}

public void paint(Graphics g) {

    Random set = new Random();
    int num1;
    num1 = set.nextInt(4);

    if (num1 == 0) {
        g.setColor(Color.blue);
        g.fillOval(x, y, radius * 2, radius * 2);
    }
    if (num1 == 1) {
        g.setColor(Color.green);
        g.fillOval(x, y, radius * 2, radius * 2);
    }
    if (num1 == 2) {
        g.setColor(Color.white);
        g.fillOval(x, y, radius * 2, radius * 2);
    }
    if (num1 == 3) {
        g.setColor(Color.magenta);
        g.fillOval(x, y, radius * 2, radius * 2);
    }
}
hpopiolkiewicz
  • 3,281
  • 4
  • 24
  • 36
Cameron
  • 3
  • 1

1 Answers1

0

Declare this field in your class, outside of a method.

Timer timer = new Timer();

Declare this method.

public void setTimerToChangeColors() {  
    timer.schedule(new TimerTask() {
      @Override
      public void run() {
        // Whatever you want your ball to do to changes its colors
        setTimerToChangeColors();
      }
    }, 10*1000); // 10 seconds * 1000ms per second
}

You only need to call setTimerToChangeColors once. It will continue restarting itself every 10 seconds. You can fill in the code for what you want to do when the task is triggered. If you want random time, you will have to edit where the timer is scheduled 10*1000 to a random generator.

Compass
  • 5,867
  • 4
  • 30
  • 42