[英]how to put a timer on a JLabel to update itself every second
我創建了一個游戲,並在我的 swing GUI 界面中放置了一個計時器。 我目前這樣做的方式是有一個帶有當前時間的字段,使用System.currentTimeMillis()
獲得它在游戲開始時獲取它的值。在我的游戲方法中,我放置了System.currentTimeMillis()
- 字段; 它會告訴您自游戲開始以來經過的當前時間。
盡管如此,可以說如何讓它每秒更新一次,所以JLabel
將具有:timePassed: 0s、timePassed: 1s 等等。 請記住,我在任何時候都不會在我的游戲中使用線程。
編輯:謝謝大家的好意建議。 我使用了您的答案的組合,請給我一些反饋。
我將 JLabel 作為一個稱為時間的字段。 (否則我無法處理)。
time = new JLabel("Time Passed: " + timePassed() + " sec");
panel_4.add(time);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
time.setText("Time Passed: " + timePassed() + " sec");
}
};
Timer timer = new Timer(1000, actionListener);
timer.start();
看看swing 定時器 class 。 它允許很容易地設置重復任務。
這就是我將 JLabel 設置為隨時間和日期更新的方式。
Timer SimpleTimer = new Timer(1000, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
jLabel1.setText(SimpleDay.format(new Date()));
jLabel2.setText(SimpleDate.format(new Date()));
jLabel3.setText(SimpleTime.format(new Date()));
}
});
SimpleTimer.start();
然后將其添加到您的主 class 並且 jlabel1/2/3 將使用計時器進行更新。
new Thread(new Runnable
{
public void run()
{
long start = System.currentTimeMillis();
while (true)
{
long time = System.currentTimeMillis() - start;
int seconds = time / 1000;
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
label.setText("Time Passed: " + seconds);
}
});
try { Thread.sleep(100); } catch(Exception e) {}
}
}
}).start();
在構造函數中寫這個
ActionListener taskPerformer = new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
jMenu11.setText(CurrentTime());
}
};
Timer t = new Timer(1000, taskPerformer);
t.start();
而這個寫出構造函數
公共字符串當前時間(){
Calendar cal = new GregorianCalendar();
int second = cal.get(Calendar.SECOND);
int min = cal.get(Calendar.MINUTE);
int hour = cal.get(Calendar.HOUR);
String s=(checkTime(hour)+":"+checkTime(min)+":"+checkTime(second));
jMenu11.setText(s);
return s;
}
public String checkTime(int t){
String time1;
if (t < 10){
time1 = ("0"+t);
}
else{
time1 = (""+t);
}
return time1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.