Easy Way to implement A Dynamic Clock in Java using Threads

Introduction: In this Tutorial, creation of clock which updates every second is explained. Here we create an Application for clock. It shows Hour, minutes and seconds which updates every second. Main Idea: The Dynamic clock can be created using Java's Timer thread but here we will see how to use our own thread and accomplish the task. This tutorial can clear any doubts you have in Java Threads. The Code which is to repeated or updated(the task) can be placed in Thread's run method. Solution Description: Step 1: Firstly we have to create a class which extends JFrame in order to create an Application. We also need it to implement Runnable Interface in order to create and run Threads. Also WidowsListener Interface to enable closing the Application when window close button is pressed. Step 2: We need a Thread 'timer' which should be null initially. A JLabel to display the Clock text, a variable for storing date, a variable curr_Time to store the time to be displayed, it should be of String data type. Step 3: We create constructor of class in which we create a JPanel object and set FlowLayout to it and add a label to it. Java's Date method returns date in long date format, to display the time in specific format we create a method formatTime() which returns formated time(String). To get current hour, minute, second, methods like getHour() of Date object are used. To know whether the time is AM or PM, it is compared with 12. In order to display 12 hour time, 12 is subtracted from the time if it exceeds 12. concat() method of String class is used to concatenate hour, minute and second. To display the time in “00:00:00” format padElement(int expr, char padchar) is used which pads the padchar('0') to the left if number is less than 10. Step 4: For the Dynamic clock the start() method initializes the timer Thread object and calls it's start() method. Stop() method stops the thread by making it null and finally the run() method is used to update it every second. Run() method tries to sleep for certain time and then runs a task. The task includes getting the current time by using Date object and then calling the formatTime function to get the time to be displayed in the specific format. This task runs while the timer Thread object is not null. Step 5: In the windowClosing() method of WindowListener, stop() method is called so that thread stops running and System's exit() method is called in order to exit the Application. Step 6: Finally in the main() method we have to create the object of the main class and call it's start() method to start the clock. Complete code looks like below.
  1. import java.awt.Color;
  2. import java.awt.Container;
  3. import java.awt.FlowLayout;
  4. import java.awt.Font;
  5. import javax.swing.JFrame;
  6. import java.awt.event.WindowEvent;
  7. import java.awt.event.WindowListener;
  8. import java.util.Date;
  9.  
  10.  
  11. import javax.swing.JLabel;
  12.  
  13.  
  14.  
  15. import javax.swing.UIManager;
  16. import javax.swing.UnsupportedLookAndFeelException;
  17.  
  18.  
  19. public class Clock extends JFrame implements Runnable, WindowListener{
  20.  
  21. Thread timer=null;
  22.  
  23. String dateToDisplay;
  24.  
  25. int hr;
  26. Date d;
  27. JLabel dateLabel=new JLabel();
  28. int hour;
  29. int minute;
  30. int second;
  31. String amPm="AM";
  32.  
  33. public static void main(String[] args) {
  34. Clock clock=new Clock();
  35. clock.setSize(200, 80);
  36. clock.setVisible(true);
  37. try {
  38. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  39.  
  40. }
  41.  
  42. } catch (InstantiationException e) {
  43.  
  44. } catch (IllegalAccessException e) {
  45.  
  46.  
  47. }
  48. clock.setResizable(false);
  49. clock.start();
  50.  
  51.  
  52. }
  53.  
  54. private void start() {
  55. if(timer == null)
  56. {
  57. timer = new Thread(this);
  58. timer.start();
  59. }
  60. }
  61.  
  62. public void stop()
  63. {
  64. timer = null;
  65. }
  66.  
  67. Clock()
  68. {
  69.  
  70. this.setLayout(new FlowLayout());
  71.  
  72. dateLabel.setBackground(Color.GRAY);
  73. dateLabel.setForeground(Color.MAGENTA);
  74. dateLabel.setFont(new Font("Anklepants",Font.PLAIN,16));
  75.  
  76. this.add(dateLabel);
  77. this.setTitle("Clock ");
  78. this.pack();
  79. this.setLocationRelativeTo(null);
  80.  
  81. }
  82. public String getFormatedDate(Date d)
  83. {
  84. String formatedDate=" ";
  85. hour = d.getHours();
  86. minute = d.getMinutes();
  87. second = d.getSeconds();
  88. amPm=(hour<12)?"AM":"PM";
  89. hr=(hour>12)?hour-12:hour;
  90.  
  91. formatedDate=formatedDate.concat(padElement(hr, '0'));
  92. formatedDate=formatedDate.concat(":");
  93. formatedDate=formatedDate.concat(padElement(minute, '0'));
  94. formatedDate=formatedDate.concat(":");
  95. formatedDate=formatedDate.concat(padElement(second, '0'));
  96. formatedDate=formatedDate.concat(" "+ amPm);
  97. return formatedDate;
  98. }
  99.  
  100. private String padElement(int expr, char padChar)
  101. {
  102. String result = "";
  103. // I'm just padding 2 digit numbers
  104. if (expr < 10) result = result.concat(String.valueOf(padChar));
  105. result = result.concat(String.valueOf(expr));
  106. return(result);
  107. }
  108.  
  109.  
  110. public void run() {
  111. // Sleep in the timer thread...
  112. while (timer != null) {
  113. try {timer.sleep(10);}
  114. catch (InterruptedException e){}
  115. d=new Date();
  116. dateToDisplay=getFormatedDate(d);
  117. dateLabel.setText(dateToDisplay);
  118. }
  119. timer = null;
  120.  
  121. }
  122.  
  123.  
  124. public void windowActivated(WindowEvent arg0) {
  125. // TODO Auto-generated method stub
  126.  
  127. }
  128.  
  129. public void windowClosed(WindowEvent arg0) {
  130. }
  131. public void windowClosing(WindowEvent arg0) {
  132. stop();
  133. dispose();
  134. System.exit(0);
  135.  
  136. }
  137. public void windowDeactivated(WindowEvent arg0) {
  138. }
  139. public void windowDeiconified(WindowEvent arg0) {
  140. }
  141. public void windowIconified(WindowEvent arg0) {
  142. }
  143. public void windowOpened(WindowEvent arg0) {
  144. }
  145.  
  146. }

Comments

Submitted byIsabelle (not verified)on Tue, 01/28/2014 - 23:05

Hey I am learning core java and I cannot tell you how much this helped me. Kudos to you! You really are a genius.

Add new comment