我已經在互聯網上搜索試圖找到如何使一個自動更新時鐘gui程序沒有運氣。我嘗試了許多不同的方法,並以相同的結果結束。我正在使用swing Timer,因爲我已經讀過這是處理gui的最好方法。我嘗試過驗證(),重新驗證(),repaint()。 下面是部分代碼:JLabel沒有更新與計時器
import javax.swing.*;
//import java.awt.event.*;
import java.util.*;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ClockPanel extends JPanel {
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int month = now.get(Calendar.MONTH) + 1;
int day = now.get(Calendar.DAY_OF_MONTH);
int year = now.get(Calendar.YEAR);
private String currentTime;
private JLabel current;
public ClockPanel() {
super();
currentTime = getTime();
current = new JLabel(currentTime);
add(current);
ActionListener updater = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
getTime();
if(second == 60){
current.setText(currentTime);
revalidate();
}
getTime();
}
};
Timer timer = new Timer(1000, updater);
timer.start();
}
這是我結束了最後的代碼;我知道這是錯誤的,但我已經改變了這麼多好幾個小時,我放棄了。由於
編輯:這裏是你調用getTime()
代碼
public String getTime() {
String time;
String period = "AM";
String monthName = "";
switch(month) {
case (1):
monthName = "January";
break;
case (2):
monthName = "February";
break;
case (3):
monthName = "March";
break;
case (4):
monthName = "April";
break;
case (5):
monthName = "May";
break;
case (6):
monthName = "June";
break;
case (7):
monthName = "July";
break;
case (8):
monthName = "August";
break;
case (9):
monthName = "September";
break;
case (10):
monthName = "October";
break;
case (11):
monthName = "November";
break;
case (12):
monthName = "December";
break;
}
if(hour >= 12){
period = "PM";
}
time = monthName + " " + day + ", " + year + " "
+ hourCheck(hour) + ":" + minuteCheck(minute) + period;
return time;
}
private int hourCheck(int hour) {
if(hour > 12){
hour -= 12;
return hour;
}
if(hour == 0) {
hour += 12;
return hour;
}
return hour;
}
private StringBuilder minuteCheck(int minute) {
StringBuilder time = new StringBuilder();
if(minute < 10) {
return time.append("0").append(minute);
}
else {
time.append("").append(minute);
}
return time;
}
}
代碼中的任何編譯器錯誤...?它似乎 – pinkpanther
你可以發佈方法'getTime()'的代碼嗎? – Genzer
編譯器內部沒有任何錯誤。我使用NetBeans,如果有幫助 – TechnicalCustoms