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();
}
}
this Localdatetime captures the time, but it does not update it at runtime ?
– user59442
@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?
– user28595
that’s right! It’s possible ?
– user59442
@Updated Java response
– user28595
Thank you very much !
– user59442
I think use
Timer t = new Timer(1000, ae -> setText(getDateTime()));
better, because it dispenses theClockLabel
of having to publicly implement an interface that is just an implementation detail that should be private, thus resulting in a better encapsulation.– Victor Stafusa
Your
main
should haveEventQueue.invokeLater(() -> new TelaSistema());
- read that question to understand why.– Victor Stafusa
@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.
– user28595
I made the change and added the link you mentioned about the EDT.
– user28595
Did you not understand my comment about the
ClockLabel
. I think the class is great. My question is about theimplements ActionListener
.– Victor Stafusa