How To Make Digital Clock In Swing Java
Digital Clock in Swing
We can easily make the digital clock in Swing Java.
Let’s see an example of the digital clock, given below.
Code
- import javax.swing.*;
- import java.awt.*;
- import java.text.*;
- import java.util.*;
- public class DigitalClockExample implements Runnable {
- JFrame jf;
- Thread t = null;
- int hours = 0, minutes = 0, seconds = 0;
- String timeString = "";
- JButton b;
- DigitalClockExample() {
- jf = new JFrame();
- t = new Thread(this);
- t.start();
- b = new JButton();
- b.setBounds(150, 150, 150, 60);
- jf.add(b);
- jf.setSize(400, 400);
- jf.setLayout(null);
- jf.setVisible(true);
- }
- public void run() {
- try {
- while (true) {
- Calendar cal = Calendar.getInstance();
- hours = cal.get(Calendar.HOUR_OF_DAY);
- if (hours > 12) {
- hours -= 12;
- }
- minutes = cal.get(Calendar.MINUTE);
- seconds = cal.get(Calendar.SECOND);
- SimpleDateFormat f = new SimpleDateFormat("hh:mm:ss");
- Date d = cal.getTime();
- timeString = f.format(d);
- printTime();
- t.sleep(1000);
- }
- } catch (Exception e) {
- }
- }
- public void printTime() {
- b.setText(timeString);
- }
- public static void main(String[] args) {
- new DigitalClockExample();
- }
- }
Output
Summary
Thus, we learnt how to make the digital clock in Swing Java.