In this example you’ll see how to use java.swing.Timer
class to create a text clock program.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class TimerDemo extends JFrame {
public static final DateFormat df = new SimpleDateFormat("hh:mm:ss");
public TimerDemo() throws HeadlessException {
initUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TimerDemo().setVisible(true));
}
private void initUI() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(500, 500);
Container container = getContentPane();
container.setLayout(new FlowLayout(FlowLayout.CENTER));
final JLabel label = new JLabel();
container.add(label);
Timer timer = new Timer(1000, e -> {
Calendar now = Calendar.getInstance();
String timeText =
"<html><font size='10' color='blue'>" +
df.format(now.getTime()) +
"</font></html>";
label.setText(timeText);
});
timer.start();
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024