A digital clock is a format of hours, minutes and seconds. To display the digital clock in java, use the ‘Swing’.
Let us implement the digital clock.
Logic:
- A frame is created.
- Basic settings like title, size,layout, label are set.
- The clock format is displayed in the label.
Java implementation:
The built-in packages javax.swing, java.awt, java.text.SimpleDateFormat and java.util.Date are included.
- Create a public class which extends JFrame.
- A label object is created.
- In the constructor(), add the following.
- setTitle() – it adds the title.
- setSize() – length and breadth are created.
- setDefaultCloseOperation -it makes the window closing method.
- setLayout – it sets the layout.
- Label object is initialised.
- Label font name,size and Boldness are assigned.
- Make the label set in the center of the border layout.
- A timer is set to update the clock.
- Make the visibility to true.
- To update the clock, make the date format as hour,minute and second.
- Make the timer displayed in the label.
- Finally, create the main() function.
- Call the SwingUtilities.invokeLater() function to display the clock.
Program:
// Built –in packages
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
// public class creation
public class DigitalClockEg extends JFrame {
private JLabel
clockLabel1;
//constructor
public
DigitalClockEg() {
// Basic settings are created.
setTitle("DigiClock");
setSize(250,
100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new
BorderLayout());
clockLabel1 =
new JLabel("", SwingConstants.CENTER);
clockLabel1.setFont(new Font("Times New Roman", Font.BOLD,
27));
clockLabel1.setForeground(Color.RED);
add(clockLabel1, BorderLayout.CENTER);
new
Timer(1000, e -> updateClock()).start();
setVisible(true);
}
//updateClock()
function definition
private void
updateClock() {
String cTime1
= new SimpleDateFormat("HH:mm:ss").format(new Date());
clockLabel1.setText(cTime1);
}
//main() function
public static void
main(String[] args) {
SwingUtilities.invokeLater(DigitalClockEg::new);
}
}
Output:
Just Compile and run the program to get the output as
follows….
C:\raji\blog>javac DigitalClockEg.java
C:\raji\blog>java DigitalClockEg
This is the way of creating a digital Clock in java Swing.
Hope, this code is helpful to you. If you have any queries, drop your comments
in the comment section. Keep coding!!!