Date - Calendar - System date in JAVA in real time Thread

-2

I try to add to a JLabel the date and time of the current system running the application. It shows me the date and time of the system when launching / executing the file JAVA but it does not update it at the time of execution of the program.

How can I fix it?

        //Creamos un objeto de la clase Calendar.
        Calendar fecha = new GregorianCalendar();
        //Obtenemos el valor del año, mes, día, hora, minuto y segundo del sistema.
        //Usando el método get y el parámetro correspondiente.
        int ano = fecha.get(Calendar.YEAR);
        int mes = fecha.get(Calendar.MONTH);
        int dia = fecha.get(Calendar.DAY_OF_MONTH);
        int hora = fecha.get(Calendar.HOUR_OF_DAY);
        int minuto = fecha.get(Calendar.MINUTE);
        int segundo = fecha.get(Calendar.SECOND);
        //System.out.println("Fecha Actual: "+dia+ "/" +(mes+1)+ "/" +ano);
        //System.out.printf("Hora Actual: %02d:%02d:%02d %n", hora, minuto, segundo);
        label_fechasistema.setText(""+dia+"/"+mes+1+"/"+ano+"    "+hora+":"+minuto+":"+segundo);

Image: link

    
asked by omaza1990 10.01.2017 в 21:34
source

2 answers

2
import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
/**
 *
 * @author aandres
 */
public class RelojModeloUtil extends Observable
 {
     /**
      * Lanza un timer cada segundo.
      */
     public RelojModeloUtil()
     {
         Timer timer = new Timer();
         timer.scheduleAtFixedRate(timerTask, 0, 1000);
     }

     /**
      * main de prueba de esta clase.
      * No necesita una ventana para funcionar.
      */
     public static void main (String [] args)
     {
         RelojModeloUtil modelo = new RelojModeloUtil();
         modelo.addObserver (new Observer()
         {
             public void update (Observable unObservable, Object dato)
             {
                 System.out.println (dato);
             }
         });
     }

     /**
      * Clase que se mete en Timer, para que se le avise cada segundo.
      */
     TimerTask timerTask = new TimerTask()
     {
         /**
          * Método al que Timer llamará cada segundo. Se encarga de avisar
          * a los observadores de este modelo.
          */
         public void run() 
         {
             setChanged();
             notifyObservers(new Date());
         }
     };
}

The Visual Clock class

import java.awt.Dimension;
import java.text.SimpleDateFormat;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

/**
 * Visual para mostrar el reloj.
 * Es un JLabel que recibe un Observable de cambio de fecha.
 */
public class RelojVisual extends JLabel
 {
     /**
      * Se pasa un observable de fecha/hora. El Observable debe pasar un
      * Date a esta visual para que la presente.
      */
     public RelojVisual(Observable modelo)
     {
         // La fecha/hora se pinta en el centro de este JLabel
         this.setHorizontalAlignment((SwingConstants.CENTER));

         // Suscripción al cambio de fecha/hora en el modelo recibido.
         modelo.addObserver (new Observer ()
         {
             // Método al que el Observable llamará cuando se cambie
             // la fecha/hora. El arg se espera que sea un Date.
             public void update(java.util.Observable o, Object arg) 
             {
                 final Object fecha = arg;

                 // Se actualiza en pantalla la fecha/hora.
                 SwingUtilities.invokeLater (new Runnable()
                 {
                     public void run()
                     {
                         setText (format.format(fecha));
                     }
                 });
             }
         });

         // Se da una dimension al JLabel.
         this.setPreferredSize(new Dimension (200, 50));
     }

     /**
      * Cambia el formato de presentacion de la fecha/hora en pantalla.
      */
     public void setFormat (SimpleDateFormat unFormato)
     {
         format = unFormato;
     }

     /**
      * Clase para mostrar una fecha/hora en formato texto.
      */
    SimpleDateFormat format = new SimpleDateFormat ("dd/MM/yyyy hh:mm:ss");
}

Finally you have a clock component that you can add to any part of your system in the following way:

RelojVisual r = new RelojVisual(new RelojModeloUtil());
frame.add(r);
    
answered by 10.01.2017 в 21:57
-1

Angeldev's option is valid. As well said SJuan76, I must use Thread . We launch a thread which integrates into a JLabel tag within JFrame the current system time, I can get it with both the Date class and the Calendar class.

Hora.java

public class Hora extends Thread{
    private JLabel etiqueta;
    public Hora(JLabel etiqueta){
       this.etiqueta = etiqueta;
    }

    @Override
    public void run(){
        while(true){
           Date hoy = new Date();
           SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
           etiqueta.setText(sdf.format(hoy));
           try{
              sleep(1000); //Segundo a segundo... 
           }catch(Exception e){
              e.getMessage();
           }
       }
   }
}

Index.java

public class Index extends javax.swing.JFrame {
    public Index() {
        initComponents();
        Hora hilo = new Hora(etiqueta);
        hilo.start();
    }
}
    
answered by 11.01.2017 в 09:28