final Timer timer = new Timer(10, new ActionListener() {
long startTime = -1;
@Override
public void actionPerformed(ActionEvent event) {
..................
..................
}
});
這解決了這個小問題。現在你還有另外一個問題,你不能在定時器的actionPerformed事件中使用Timer.stop()方法在你自己內部使用Timer.stop()方法啓動並停止Timer(例如:timer.stop();)出於簡單的原因,變量計時器在那裏沒有適當的範圍,並且看不到它已經被初始化。是的,它可能會編譯,它很可能會運行直到timer.stop()方法被調用,然後你會最終得到一個運行時異常(「變量定時器可能沒有被初始化」)。不好,不要考慮捕捉異常,並讓過去的過去,因爲你最終不會停止定時器(蹩腳的做法)。你只需要得到一個小票友你停止,這將這樣的伎倆:
((Timer)event.getSource()).stop();
//event is the ActionEvent variable (usually evt in some IDE's).
現在,您時間變量,沒有什麼不對的,如果你想甚至1提供長期數值分鐘的時間。如果那是你的事情,但是對我個人而言,這很好,我喜歡簡單地輸入60而不是60000。它的值是否會硬編碼到位,但如果它實際上是一個提供的值(不管從哪裏),那麼真的沒關係,那麼提供秒(IMHO)會更好,這當然需要使用額外的變量,例如:
int seconds = 10;
final long duration = seconds * 1000;
現在您只需提供想要設置倒數計時器的秒數。
你有另一個問題是,你聲明的變量命名標籤代表一個JLabel,但沒有在任何地方你要麼引用該變量的實際JLabel的地方,或者將其添加到框架或面板組件。我想,您已經在GUI中安裝一個JLabel(如果你有一個GUI)在這種情況下,當你聲明標籤變量,這樣你就需要提供一個JLabel的變量名:
JLabel label = (JLabel)jLabel1;
通過這種方式,標籤變量代表在GUI中名爲jLabel1的JLabel。
最後(這是一個biggy)你的計時器不會運行,如果你不告訴它這樣做。你在哪裏做,好了,就在你當然本地定時器類:)這樣的:
final Timer timer = new Timer(10, new ActionListener() {
long startTime = -1;
@Override
public void actionPerformed(ActionEvent event) {
..................
..................
}
});
timer.start();
不管怎麼說,這裏是如許的完整代碼:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
int seconds = 10; // supply timer duration in seconds
final long duration = seconds * 1000; // calculate to milliseconds
JLabel label = (JLabel)jLabel1; //whichever JLabel is in GUI
final Timer timer = new Timer(10, new ActionListener() {
long startTime = -1;
@Override
public void actionPerformed(ActionEvent event) {
if (startTime < 0) {
startTime = System.currentTimeMillis();
}
long now = System.currentTimeMillis();
long clockTime = now - startTime;
if (clockTime >= duration) {
clockTime = duration;
((Timer)event.getSource()).stop(); // stop the Timer
label.setText("Time Is UP"); // remove if you want or maybe just ""
return;
}
SimpleDateFormat df = new SimpleDateFormat("mm:ss:SSS");
label.setText(df.format(duration - clockTime));
}
});
timer.start();
}
'新的JLabel; '...? – Tunaki
你想用這段代碼實現什麼?如果你想要一個可以鎖定一段時間的按鈕,請爲此創建一個類 –
我想在Jpanel中添加此代碼,但我不知道該怎麼做。即使我添加了它並創建了一個類,JPanel也沒有向我顯示計時器@JarlikStepsto –