Pregunta

Usé el siguiente programa para obtener el reloj. ¿Qué resultó ser un reloj estático ?¿Por qué es así?

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();
    } 
} 
¿Fue útil?

Solución

GregorianCalendar() Construye un GregorianCalendar predeterminado usando la hora actual en la zona horaria predeterminada con la configuración regional predeterminada. Documento de Java

Puede hacerlo de esta manera.

while(true) {
       GregorianCalendar gc = new GregorianCalendar();
   l.setText(gc.get(gc.HOUR) + ":" + gc.get(gc.MINUTE) + ":" + gc.get(gc.SECOND));
}

¡Ahora debe comprender por qué obtiene un reloj estático!

Otros consejos

Solo crea el GregorianCalendar una vez y nunca se actualiza.Entonces, la fecha es siempre la misma.

hay grandes problemas además del que ha detectado:

  • no dejes que los subprocesos se vuelvan locos, eventualmente congelarán la interfaz de usuario
  • todos y cada uno de los accesos a un componente Swing deben ocurrir en el EDT

Puede resolver ambas cosas de la manera más fácil usando un javax.swing.Timer

ActionListener nextSecond = new ActionListener() {
     @Override
     public void actionPerformed(ActionEvent e) {
         // get time ...
         timeLabel.setText(...);
     }
}
new Timer(1000, nextSecond).start();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top