Like the one we add into the corner of presentation slides.
I already have SwingX library added and working, in case that could help with something.
Basically, you want to use a JLabel
for displaying the date/time, a javax.swing.Timer
set to a regular interval to update the label and a DateFormat
instance to format the date value...
public class PlaySchoolClock {
public static void main(String[] args) {
new PlaySchoolClock();
}
public PlaySchoolClock() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ClockPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ClockPane extends JPanel {
private JLabel clock;
public ClockPane() {
setLayout(new BorderLayout());
clock = new JLabel();
clock.setHorizontalAlignment(JLabel.CENTER);
clock.setFont(UIManager.getFont("Label.font").deriveFont(Font.BOLD, 48f));
tickTock();
add(clock);
Timer timer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tickTock();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.setInitialDelay(0);
timer.start();
}
public void tickTock() {
clock.setText(DateFormat.getDateTimeInstance().format(new Date()));
}
}
}
This example uses a time interval of half a second. The main reason for this is I don't go to the trouble of trying to calculate how far we are away from the next second when we set up the initial delay. This ensures that we are always up-to-date
The next question is to ask "why?" This kind of setup is relatively expensive, with the timer firing every half second (to catch any edge cases) and updating the screen, when most OS's actually have a date/time already on the screen...IMHO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With