• Register now to get access to thousands of Tutorials, Leaked content, Hot NSFW and much more. Join us as we build and grow the community.

Advertise Here

Advertise Here

Advertise Here

Easy Way to implement A Dynamic Clock in Java using Threads

MoistyB

Crypto Gaming Pro
M Rep
0
0
0
Rep
0
M Vouches
0
0
0
Vouches
0
Posts
141
Likes
149
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 2 1000 XP
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. import

    javax.swing.JLabel

    ;



  10. import

    javax.swing.UIManager

    ;
  11. import

    javax.swing.UnsupportedLookAndFeelException

    ;


  12. public

    class

    Clock extends

    JFrame

    implements

    Runnable

    , WindowListener

    {

  13. Thread

    timer=

    null

    ;

  14. String

    dateToDisplay;

  15. int

    hr;
  16. Date

    d;
  17. JLabel

    dateLabel=

    new

    JLabel

    (

    )

    ;
  18. int

    hour;
  19. int

    minute;
  20. int

    second;
  21. String

    amPm=

    "AM"

    ;

  22. public

    static

    void

    main(

    String

    [

    ]

    args)

    {
  23. Clock clock=

    new

    Clock(

    )

    ;
  24. clock.setSize

    (

    200

    , 80

    )

    ;
  25. clock.setVisible

    (

    true

    )

    ;
  26. try

    {
  27. UIManager

    .setLookAndFeel

    (

    UIManager

    .getSystemLookAndFeelClassName

    (

    )

    )

    ;

  28. }
  29. catch

    (

    ClassNotFoundException

    e)

    {

  30. }

    catch

    (

    InstantiationException

    e)

    {

  31. }

    catch

    (

    IllegalAccessException

    e)

    {

  32. }

    catch

    (

    UnsupportedLookAndFeelException

    e)

    {

  33. }
  34. clock.setResizable

    (

    false

    )

    ;
  35. clock.start

    (

    )

    ;


  36. }

  37. private

    void

    start(

    )

    {
  38. if

    (

    timer ==

    null

    )
  39. {
  40. timer =

    new

    Thread

    (

    this

    )

    ;
  41. timer.start

    (

    )

    ;
  42. }
  43. }

  44. public

    void

    stop(

    )
  45. {
  46. timer =

    null

    ;
  47. }

  48. Clock(

    )
  49. {

  50. this

    .setLayout

    (

    new

    FlowLayout

    (

    )

    )

    ;

  51. dateLabel.setBackground

    (

    Color

    .GRAY

    )

    ;
  52. dateLabel.setForeground

    (

    Color

    .MAGENTA

    )

    ;
  53. dateLabel.setFont

    (

    new

    Font

    (

    "Anklepants"

    ,Font

    .PLAIN

    ,16

    )

    )

    ;

  54. this

    .add

    (

    dateLabel)

    ;
  55. this

    .setTitle

    (

    "Clock "

    )

    ;
  56. this

    .pack

    (

    )

    ;
  57. this

    .setLocationRelativeTo

    (

    null

    )

    ;

  58. }
  59. public

    String

    getFormatedDate(

    Date

    d)
  60. {
  61. String

    formatedDate=

    " "

    ;
  62. hour =

    d.getHours

    (

    )

    ;
  63. minute =

    d.getMinutes

    (

    )

    ;
  64. second =

    d.getSeconds

    (

    )

    ;
  65. amPm=

    (

    hour<

    12

    )

    ?

    "AM"

    :

    "PM"

    ;
  66. hr=

    (

    hour>

    12

    )

    ?

    hour-

    12

    :

    hour;

  67. formatedDate=

    formatedDate.concat

    (

    padElement(

    hr, '0'

    )

    )

    ;
  68. formatedDate=

    formatedDate.concat

    (

    ":"

    )

    ;
  69. formatedDate=

    formatedDate.concat

    (

    padElement(

    minute, '0'

    )

    )

    ;
  70. formatedDate=

    formatedDate.concat

    (

    ":"

    )

    ;
  71. formatedDate=

    formatedDate.concat

    (

    padElement(

    second, '0'

    )

    )

    ;
  72. formatedDate=

    formatedDate.concat

    (

    " "

    +

    amPm)

    ;
  73. return

    formatedDate;
  74. }

  75. private

    String

    padElement(

    int

    expr, char

    padChar)
  76. {
  77. String

    result =

    ""

    ;
  78. // I'm just padding 2 digit numbers
  79. if

    (

    expr <

    10

    )

    result =

    result.concat

    (

    String

    .valueOf

    (

    padChar)

    )

    ;
  80. result =

    result.concat

    (

    String

    .valueOf

    (

    expr)

    )

    ;
  81. return

    (

    result)

    ;
  82. }


  83. public

    void

    run(

    )

    {
  84. // Sleep in the timer thread...
  85. while

    (

    timer !=

    null

    )

    {
  86. try

    {

    timer.sleep

    (

    10

    )

    ;

    }
  87. catch

    (

    InterruptedException

    e)

    {

    }
  88. d=

    new

    Date

    (

    )

    ;
  89. dateToDisplay=

    getFormatedDate(

    d)

    ;
  90. dateLabel.setText

    (

    dateToDisplay)

    ;
  91. }
  92. timer =

    null

    ;

  93. }


  94. public

    void

    windowActivated(

    WindowEvent

    arg0)

    {
  95. // TODO Auto-generated method stub

  96. }

  97. public

    void

    windowClosed(

    WindowEvent

    arg0)

    {
  98. }
  99. public

    void

    windowClosing(

    WindowEvent

    arg0)

    {
  100. stop(

    )

    ;
  101. dispose(

    )

    ;
  102. System

    .exit

    (

    0

    )

    ;

  103. }
  104. public

    void

    windowDeactivated(

    WindowEvent

    arg0)

    {
  105. }
  106. public

    void

    windowDeiconified(

    WindowEvent

    arg0)

    {
  107. }
  108. public

    void

    windowIconified(

    WindowEvent

    arg0)

    {
  109. }
  110. public

    void

    windowOpened(

    WindowEvent

    arg0)

    {
  111. }

  112. }


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

Create an account or login to comment

You must be a member in order to leave a comment

Create account

Create an account on our community. It's easy!

Log in

Already have an account? Log in here.

452,500

350,639

350,649

Top