检票口倒计时器不会自动更新
我想在 Wicket 中实现一个倒计时器。我有一个时钟类:
public class Clock extends Label{
private static int time;
public Clock(int mytime,String id,String message){
super(id,message);
time=mytime;
this.setDefaultModelObject(message);
}
public int getTimeLeft(){
return time;
}
public void decrement(){
time--;
}
}
在这里我尝试每秒更新它:
clock.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(1)){
protected void onTimer(AjaxRequestTarget target){
clock.decrement();
target.addComponent(clock);
}
});
这不起作用,因为 onTimer
是一个 final
方法,因此不能被重写。正确的做法是什么?
I would like to implement a countdown timer in Wicket. I have a clock class:
public class Clock extends Label{
private static int time;
public Clock(int mytime,String id,String message){
super(id,message);
time=mytime;
this.setDefaultModelObject(message);
}
public int getTimeLeft(){
return time;
}
public void decrement(){
time--;
}
}
and here I attempt to update it every second:
clock.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(1)){
protected void onTimer(AjaxRequestTarget target){
clock.decrement();
target.addComponent(clock);
}
});
This doesn't work because onTimer
is a final
method and therefore cannot be overridden. What is the correct approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有两个问题。
time
出现在生成的标签标记中的什么位置?该模型仅包含消息,因此即使时间
发生变化,也不会产生任何影响。onTimer()
是最终的,即使它不是最终的,也不能保证它每秒都会被精确地调用。因此,正如 Wicket 中经常出现的那样,解决方案是将其颠倒过来,而不是将数据推送到输出中,而是让框架将其拉入。这就是您需要做的。
Clock
类,只需使用一个普通的Label
即可,无需覆盖任何内容。IModel
子类,用于存储时钟应为零的时间戳。Label
的模型,并添加 ajax 计时器行为。您的模型将是这样的:
您可能可以猜到其余的内容。
更新:还有一件事,有点明显但可能值得一提:在现实世界的应用程序中,请确保检查剩余时间不是负值。
There are two problems here.
time
appear in the generated label markup? The model simply contains the message so even iftime
is changed, it won't make any difference.onTimer()
is final, and even if it wasn't, there's no guarantee that it would be invoked precisely every second.So the solution, as so often in Wicket is to turn it upside down, instead of pushing data into your output, let the framework pull it in. This is what you need to do.
Clock
class, use just a plainLabel
with nothing overridden.IModel<String>
subclass that stores the timestamp when the clock should be at zero.getObject()
method of the model return a string that contains the difference between the clock's zero time and the current time.Label
and add the ajax timer behaviour too.Your model will be something like this:
You can probably guess the rest.
Update: just one more thing, kind of obvious but may be worth mentioning: in a real world application make sure you check that time left isn't negative.
另一个答案是最好的,但另一种选择是使用 AbstractAjaxTimerBehavior,其中 onTimer 方法不是最终的。
查看Wicket Stuff World Clock 示例的源代码,您会看到
The other answer is best, but another alternative is to use an AbstractAjaxTimerBehavior, where the onTimer method is not final.
Look at the source code for the Wicket Stuff World Clock example and you'll see