why does it always give the same time?
-
27-10-2019 - |
Question
I used the following program to get the clock.What it turned out to be is a static clock ? Why is it so ?
import java.util.*;
import java.awt.*;
import javax.swing.*;
class tester {
JFrame fr = new JFrame();
JPanel p = new JPanel();
JLabel l = new JLabel();
Date d = new Date();
GregorianCalendar gc = new GregorianCalendar();
tester() {
p.setBackground(Color.red);
l.setVisible(true);
p.add(l);
fr.add(p);
fr.setSize(200,200);
fr.setVisible(true);
startClockThread();
}
public void startClockThread() {
Runnable r = new Runnable() {
@Override
public void run() {
startClock();
}
};
new Thread(r).start();
}
public void startClock() {
l.setVisible(true);
while(true) {
l.setText(gc.get(gc.HOUR) + ":" + gc.get(gc.MINUTE) + ":" + gc.get(gc.SECOND));
System.out.println(gc.get(gc.SECOND));
}
}
public static void main(String args[]) {
new tester();
}
}
Solution
GregorianCalendar()
Constructs a default GregorianCalendar using the current time in the default time zone with the default locale. Java Doc
You can do this way.
while(true) {
GregorianCalendar gc = new GregorianCalendar();
l.setText(gc.get(gc.HOUR) + ":" + gc.get(gc.MINUTE) + ":" + gc.get(gc.SECOND));
}
Now you should understand why you are getting a static clock !
OTHER TIPS
You only create the GregorianCalendar once, and it never gets updated. So the date is always the same.
there's are big problems apart from the one you have spotted:
- dont let threads run wild, they'll freeze the ui eventually
- each and every access to a Swing component must happen on the EDT
You can solve both easiest by using a javax.swing.Timer
ActionListener nextSecond = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// get time ...
timeLabel.setText(...);
}
}
new Timer(1000, nextSecond).start();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow