我正在學習使用GUI顯示時間減少來實現倒數計時器。我正在使用Groovy的@Bindable
,希望可以在相應的UI標籤中自動顯示時間縮短的更改。@Bindable變量在不同線程中的變化可以反映出相應的UI元素嗎?
倒計時時間值的減少是在定時器線程中完成的,與UI線程分離。但是,倒數計時器並未在用戶界面中更新。
如何正確更新用戶界面中的倒計時時間?
import groovy.swing.SwingBuilder
import java.awt.FlowLayout as FL
import javax.swing.BoxLayout as BXL
import javax.swing.JFrame
import groovy.beans.Bindable
import java.util.timer.*
// A count-down timer using Bindable to reflcet the reduction of time, when the reduction is done in a TimerTask thread
class CountDown {
int delay = 5000 // delay for 5 sec.
int period = 60*1000 // repeat every minute.
int remainingTime = 25*60*1000
// hope to be able to update the display of its change:
@Bindable String timeStr = "25:00"
public void timeString() {
int seconds = ((int) (remainingTime/1000)) % 60 ;
int minutes =((int) (remainingTime/(1000*60))) % 60;
timeStr = ((minutes < 9) ? "0" : "") + String.valueOf (minutes) + ":" + ((seconds < 9) ? "0" : "") + String.valueOf (seconds)
}
public void update() {
if (remainingTime >= period)
remainingTime = (remainingTime - period)
// else // indicate the timer expires on the panel
// println remainingTime
// convert remainingTime to be minutes and secondes
timeString()
println timeStr // this shows that the TimerTaskCountDown thread is producting the right reduction to timeStr
}
}
model = new CountDown()
class TimerTaskCountDown extends TimerTask {
public TimerTaskCountDown (CountDown modelIn) {
super()
model = modelIn
}
CountDown model
public void run() {
model.update() // here change to model.timeStr does not reflected
}
}
Timer timer = new Timer()
timer.scheduleAtFixedRate(new TimerTaskCountDown(model), model.delay, model.period)
def s = new SwingBuilder()
s.setVariable('myDialog-properties',[:])
def vars = s.variables
def dial = s.dialog(title:'Pomodoro', id:'working', modal:true,
// locationRelativeTo:ui.frame, owner:ui.frame, // to be embedded into Freeplane eventually
defaultCloseOperation:JFrame.DISPOSE_ON_CLOSE, pack:true, show:true) {
panel() {
boxLayout(axis:BXL.Y_AXIS)
panel(alignmentX:0f) {
flowLayout(alignment:FL.LEFT)
label text: bind{"Pomodoro time: " + model.timeStr}
}
panel(alignmentX:0f) {
flowLayout(alignment:FL.RIGHT)
button(action: action(name: 'STOP', defaultButton: true, mnemonic: 'S',
closure: {model.timeStr = "stopped"; vars.ok = true//; dispose() // here the change to model.timeStr gets reflected in the label
}))
}
}
}
由於缺乏直接的答案,我已經找到了最接近的例子在Java中與「搖擺定時器」的發現http://stackoverflow.com/questions/2576353/stop-a-stopwatch/2576909#2576909 – 2011-12-26 23:59:51