我在整个互联网上搜索,试图找到如何制作一个自动更新时钟 gui 程序,但没有运气。我尝试了许多不同的方法,以相同的结果结束。我正在使用摇摆计时器,因为我已经读过这是处理 gui 的最佳方式。我试过 validate()、revalidate()、repaint()。以下是部分代码:
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();
}
这是我最终得到的最终代码;我知道这是错误的,但我已经改变了几个小时,以至于我放弃了。谢谢
编辑:这是其余的代码
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;
}
}