【问题标题】:Countdown clock in GWTGWT 中的倒计时时钟
【发布时间】:2011-07-17 16:58:14
【问题描述】:
我想在 GWT 中创建一个倒计时时钟,但我找不到等待一秒的正确函数。我尝试使用 Thread.Sleep() 但我认为这是出于另一个目的。
你能帮助我吗?这是我的代码。
int count=45;
RootPanel.get("countdownLabelContainer").add(countdown);
for(int i=count; i>=0; i--)
{
countdown.setText(Integer.toString(i));
// Place here the wait-for-one-second function
}
【问题讨论】:
标签:
java
javascript
gwt
clock
【解决方案1】:
试试Timer (See Here)。
将示例代码快速更改为接近您想要的内容,但您需要根据您的目的对其进行改进:
public class TimerExample implements EntryPoint, ClickListener {
int count = 45;
public void onModuleLoad() {
Button b = new Button("Click to start Clock Updating");
b.addClickListener(this);
RootPanel.get().add(b);
}
public void onClick(Widget sender) {
// Create a new timer that updates the countdown every second.
Timer t = new Timer() {
public void run() {
countdown.setText(Integer.toString(count));
count--;
}
};
// Schedule the timer to run once every second, 1000 ms.
t.schedule(1000);
}
}
这听起来像是您正在寻找的一般领域的东西。请注意,您可以使用 timer.cancel() 来停止计时器。您需要将此与您的计数联系起来(当 45 命中 0 时)。
【解决方案2】:
下面的 sn-p 显示了计时器的使用。它显示了如何正确安排计时器以及如何取消它。
// Create a new timer that updates the countdown every second.
Timer t = new Timer() {
int count = 60; //60 seconds
public void run() {
countdown.setText("Time remaining: " + Integer.toString(count) + "s.");
count--;
if(count==0) {
countdown.setText("Time is up!");
this.cancel(); //cancel the timer -- important!
}
}
};
// Schedule the timer to run once every second, 1000 ms.
t.scheduleRepeating(1000); //scheduleRepeating(), not just schedule().