Display Current Time in Java GUI
Submitted by donbermoy on Sunday, May 4, 2014 - 11:30.
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.
3. Initialize your variable because we will just use JTextField here.
4. Create your constructor named ClockText(). This will instantiate the Main of the program.
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.
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
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import java.util.*;
- public ClockText() {
- content.add(clockField);
- this.setContentPane(content);
- this.setTitle("Time");
- this.pack();
- this.setLocationRelativeTo(null);
- this.setResizable(false);
- t.start();
- }
- clockField.setText("" + h + ":" + m + ":" + s);
- }
Add new comment
- 472 views