2014-10-02 67 views
0

我想设置一个计时器类来控制球何时选择一种新颜色。我需要在设定的时间改变球的颜色,而不是连续设置不同的颜色。这是我的球类,整个课程都是通过开课。设置一个计时器来控制何时执行随机变量

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

问题是什么? – Compass 2014-10-02 16:59:53

+0

我只需要有人解释如何使用计时器类来使我的随机变量在设定的时间段内执行。我是新来的代码,我找不到任何其他资源来帮助我。 – Cameron 2014-10-02 17:23:44

+0

请问[this](http://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java)有效吗? – Compass 2014-10-02 17:28:26

回答

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到一个随机发生器。

相关问题