How to display date and time "at runtime"?

Asked

Viewed 2,049 times

1

I would like to know how to display the current date and time of the computer, and the time should be updated at runtime. I thought of passing an object to a label, but it did not. I’m not going to save this date, I just want it to be displayed, I wanted to put it on a label so I can position it anywhere after.

package teste;

import static java.awt.Frame.MAXIMIZED_BOTH;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.Locale;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TelaSistema extends JFrame {

    public JLabel label = new JLabel();
    public JPanel painel = new JPanel();

    public TelaSistema() {
        setExtendedState(MAXIMIZED_BOTH);
        setTitle("Teste");

        GregorianCalendar calendar = new GregorianCalendar();

        label = new JLabel("Data aqui");

        painel.add(label);
        add(painel);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String args[]) {

        TelaSistema tela = new TelaSistema();
    }
}

1 answer

3


Note: Always start the screen inside the Event-Dispatch-Thread, because swing is not Thread-Safe, and the entire GUI needs to start in this one Thread. In this reply explains better the reason for this and any problems that may occur. This other reply shows some ways to start the application within this thread.


Using the package classes java.time, you can do as below:

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TelaSistema extends JFrame {

    public JLabel label = new JLabel();
    public JPanel painel = new JPanel();

    public TelaSistema() {
        setExtendedState(MAXIMIZED_BOTH);
        setTitle("Teste");

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
        LocalDateTime timePoint = LocalDateTime.now();

        label = new JLabel(timePoint.format(fmt));

        painel.add(label);
        add(painel);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }

    public static void main(String[] args) {

        java.awt.EventQueue.invokeLater(() -> new TelaSistema()); 

    }
}

The class DateTimeFormatter is responsible for formatting the date and class LocalDateTime is one of the new API classes for working with time.


And to get the date updated in real time, you can create a Timer which forces the label to update each time, in this case, 1 second. To make it easier to work with the label, I used a class by part that extends from JLabel:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.swing.JLabel;
import javax.swing.Timer;

public class ClockLabel extends JLabel {

    public ClockLabel() {
        Timer t = new Timer(1000, e -> setText(getDateTime()));
        t.setInitialDelay(0);
        t.start();
    }

    private String getDateTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));
    }
}

Add this class to your project and then just instate it:

label = new ClockLabel();

See a working example:

GIF animado da tela


I recommend reading of this question to learn how to work with these new classes, they are optimized to work with time, and also reading of this other answer explaining some reasons to avoid working with old classes to manipulate dates.

  • this Localdatetime captures the time, but it does not update it at runtime ?

  • @Java displays the current time and date at the time of execution of that line of code. You want it to display the clock in real time?

  • that’s right! It’s possible ?

  • @Updated Java response

  • Thank you very much !

  • I think use Timer t = new Timer(1000, ae -> setText(getDateTime())); better, because it dispenses the ClockLabel of having to publicly implement an interface that is just an implementation detail that should be private, thus resulting in a better encapsulation.

  • Your main should have EventQueue.invokeLater(() -> new TelaSistema()); - read that question to understand why.

  • @Victorstafusa true, passed unnoticed the Eventqueue, copied the OP code but ended up not noticing it at the time. As for the Clocklabel class, I opted for it to give the possibility of reuse, if you have more than one screen, for example, just being able to display the hours would be more practical.

  • 1

    I made the change and added the link you mentioned about the EDT.

  • Did you not understand my comment about the ClockLabel. I think the class is great. My question is about the implements ActionListener.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.