我正在爲一所學校的項目工作,而我很困難。我已經寫了一個程序顯示當前時間,但我無法弄清楚如何隨着時間的變化來更新顯示。如果有人能幫助我,或者指引我走向某個方向,那麼您的幫助將不勝感激。我將發佈我在下面寫的內容。爪哇獲取時鐘更新
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class Project2 extends JFrame{
public static void main(String[] args){
Project2 myFrame = new Project2();
myFrame.pack();
myFrame.setTitle("Digital Clock");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLocationRelativeTo(null);
myFrame.setVisible(true);
}//main()
public Project2(){
System.out.println(currentTime());
JPanel p1 = new JPanel();
p1.setLayout(new FlowLayout());
JLabel time = new JLabel(currentTime());
time.setFont(new Font("TimesRoman", Font.BOLD, 20));
time.setForeground(Color.blue);
p1.add(time);
this.setLayout(new BorderLayout());
this.add(p1, BorderLayout.CENTER);
}
public String currentTime(){
Calendar calendar = Calendar.getInstance();
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
int aP = calendar.get(Calendar.AM_PM);
String currentTime = hours+":"+checkTime(minutes)+":"+checkTime(seconds)+" "+amP(aP);
return currentTime;
}
public String checkTime(int t){
String time1;
if (t < 10){
time1 = ("0"+t);
}
else{
time1 = (""+t);
}
return time1;
}
public String amP(int ap){
String amPm;
if(ap == 0)
amPm = "AM";
else
amPm = "PM";
return amPm;
}
}//Project2
我可以有另一個提示什麼的,我現在很失落。我看了一下Timer類,但我不確定如何實現到我的程序中。 – Gnosis
-1在Swing中使用的Timer是javax.swing.Timer,而不是util中的Timer – kleopatra