Load the current time that tick every seconds in Java

0
58

This tutorial entitled “Load the current time that tick every seconds in Java” will teach you on how to load the current time and change automatically in every seconds. I already publish about loading the current time, but this tutorial is different.  Every tick of seconds, the time also changes automatically.

The program use jLabel element to display the changeable time. Please follow all the steps to complete this tutorial.

Load the current time that tick every seconds in Java Steps

  1. Add or create a new form inside your Java project. In my case, I named my form using “DisplayTimeInJava”.

2. Design your form just look like what I do in the image below. The elements are located in your Java pallets in the right side your Netbeans window.

3. Copy all the codes below and paste it above your main class. The codes are used to access the required libraries in this program.

  1. import java.util.Calendar;
  2. import java.util.GregorianCalendar;

4. Copy the line of codes below and insert it into your main class but outside from other methods. The codes are used for integer variable declaration.

  1. int timerun = 0;

5. Inside your main class, create a new method. In my case, I used “load_clock” as my method name.

  1. public final void load_clock(){
  2.  
  3. }

6. Copy the following codes below and paste it inside your new created methods. The codes are composed of thread, calendar, and other variables use to load the time.

  1. new Thread(){
  2. public void run(){
  3. while (timerun ==0){
  4.  
  5. int hour = cal.get(Calendar.HOUR);
  6. int min = cal.get(Calendar.MINUTE);
  7. int sec = cal.get(Calendar.SECOND);
  8. int am_pm = cal.get(Calendar.AM_PM);
  9.  
  10. String day_night = "";
  11. if(am_pm == 1)
  12. {
  13. day_night = "PM";
  14. }else
  15. {
  16. day_night = "AM";
  17. }
  18.  
  19. String time = hour + ":" + min + ":" + sec + " " + day_night;
  20. jLabel1.setText(time);
  21. }
  22. }
  23. }.start();

7. Copy the method name of your new created method and paste it inside your public method after the “initComponent” variable. Public method is use to initialized and load all the functions in form load event of the program.

  1. load_clock();

8. Run your program and the output should look like the image below.

After completing this tutorial, you are now understand on how to create a program that load the current time and change it automatically based on the timer tick. If you have questions and suggestions, feel free to contact me through marjohn@kmjtech.net or you can use the contact information of this website.

Related Articles You May Like:

Facebook Comments
(Visited 59 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here