Display Current Time in Java GUI

Now, in this tutorial, i am going to teach you how to create a program that will display the current time using Java in GUI form. Of course, it is a too little hassle because java has complicated codes in showing current time compared to other languages such as visual basic. Now, let's start this tutorial! 1. Open JCreator or NetBeans and make a java program with a file name of ClockText.java. 2. Import the following packages below.
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. import java.util.*;
3. Initialize your variable because we will just use JTextField here.
  1. JTextField clockField; ;
4. Create your constructor named ClockText(). This will instantiate the Main of the program.
  1. public ClockText() {
  2.  
  3. clockField= new JTextField(5);
  4.  
  5. JPanel content = new JPanel();
  6. content.setLayout(new FlowLayout());
  7. content.add(clockField);
  8.  
  9. this.setContentPane(content);
  10. this.setTitle("Time");
  11. this.pack();
  12. this.setLocationRelativeTo(null);
  13. this.setResizable(false);
  14.  
  15. javax.swing.Timer t = new javax.swing.Timer(1000, new ClockListener());
  16. t.start();
  17.  
  18. }
The code above declares that the JTextField will have only 5 characters for showing time. We add panel though, and the textfield clockField is inside of that panel. But our focus here is that we use the Timer class of the swing package and instantiate the time of 1000 ms time interval with the instantiation of our ClockListener which will be the last step of coding the program. Then the time will start as we run our program. 5. Now, create another class that will implement an ActionListener of the time.
  1. class ClockListener implements ActionListener {
  2. public void actionPerformed(ActionEvent e) {
  3.  
  4. Calendar now = Calendar.getInstance();
  5. int h = now.get(Calendar.HOUR_OF_DAY);
  6. int m = now.get(Calendar.MINUTE);
  7. int s = now.get(Calendar.SECOND);
  8. clockField.setText("" + h + ":" + m + ":" + s);
  9.  
  10. }
We used the calendar class from the java.util package. This is also to call the Calendar methods such as the hour of the day, minute, and second. But actually there's a lot more in the calendar class like the year, month, and the day. Then, the gathered time information is displayed in the textField named clockField. Output: Add and Follow me on Facebook: https://www.facebook.com/donzzsky Mobile: 09488225971

Add new comment