To reach the solution below, it was only necessary to merge the solution of this answer with the latter another answer, since the first shows how to make a Timer
and display it at runtime on a JLabel
, and the second shows how to calculate the time difference using the new API, showing from seconds to days:
import java.time.*;
import javax.swing.*;
import java.awt.event.*;
import java.time.temporal.ChronoUnit;
public class ProgramaExemplo extends JFrame {
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ProgramaExemplo();;
}
});
}
public JLabel label = new JLabel();
public ProgramaExemplo() {
setExtendedState(MAXIMIZED_BOTH);
setTitle("---");
JPanel x = new JPanel();
x.setLayout(null);
label = new ClockLabel();
x.add(label);
label.setBounds(700, 500, 300, 200);
add(x);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
class ClockLabel extends JLabel implements ActionListener {
private LocalDateTime start;
public ClockLabel() {
this.start = LocalDateTime.now();
Timer t = new Timer(1000, this);
t.start();
setText(getDateTime(start));
}
private String getDateTime(LocalDateTime segundaDate){
Duration testeDuration = Duration.between(start, segundaDate);
long dias = testeDuration.toDays();
Duration d2 = testeDuration.minus(dias, ChronoUnit.DAYS);
long horas = d2.toHours();
Duration d3 = d2.minus(horas, ChronoUnit.HOURS);
long minutos = d3.toMinutes();
Duration d4 = d3.minus(minutos, ChronoUnit.MINUTES);
long segundos = d4.getSeconds();
Duration d5 = d4.minus(segundos, ChronoUnit.SECONDS);
long nanos = d5.toNanos();
Duration d6 = d5.minus(nanos, ChronoUnit.NANOS);
if (!d6.isZero()) throw new AssertionError(d6.toString());
return "Total: " + dias + " dias, " + horas + " horas, " + minutos + " minutos, " + segundos + " segundos";
}
@Override
public void actionPerformed(ActionEvent ae) {
setText(getDateTime(LocalDateTime.now()));
}
}
}
Working:
Of course you will need to adjust the label size, since you are using AbsoluteLayout
, as time passes, the string can increase its size.
How do you get this "running time"? In the example there is no time.
– user28595
By chance the time you’re trying to get is the same of this question?
– user28595
From what I understood "this question" the guy wants the time of the pc, I want to know how long the user is running the program, my doubt is if there is a way to do this, if yes, what I must research to understand how it works. I just want to display on a label or other component that time.
– user59450
What unit of time?
– user28595
@diegofm if you can do it, it would be nice to catch the Hour, minutes and seconds. Or at least Hour and minutes. (if you can do it)
– user59450
The idea is the same as the question I posted, together with this other.
– user28595