设置计时器以控制何时执行随机变量

时间:2014-10-02 16:44:03

标签: java random timer actionlistener timertask

我正在尝试设置一个计时器类来控制球何时选择新颜色。我需要让球在设定的时间改变颜色,而不是只是连续设置不同的颜色。这是我的球类,整个程序都是通过一个起始类运行的。

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

1 个答案:

答案 0 :(得分:0)

在方法之外的类中声明此字段。

Timer timer = new Timer();

声明此方法。

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
}

您只需要调用一次setTimerToChangeColors。它将每10秒继续重启一次。您可以填写代码,以便在触发任务时执行您想要执行的操作。如果您想要随机时间,则必须编辑定时器的计划位置10*1000到随机生成器。