문제

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();
    } 
} 
도움이 되었습니까?

해결책

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 !

다른 팁

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();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top