Create a Clock in Java:
We can use the Eclipse IDE for this example. If you do not know about it then follow this link- How to Install Eclipse For Java and create a program in it. |
SimpleDateFormat Class– Oracle Docs.
Sample Code to Create a Clock in Java:



Output:

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ClockApp extends JFrame{
SimpleDateFormat timeFormat;
SimpleDateFormat dayFormat;
SimpleDateFormat dateFormat;
JLabel timeLabel;
JLabel dayLabel;
JLabel dateLabel;
String time;
String day;
String date;
ClockApp() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Clock App");
this.setLayout(new FlowLayout());
this.setSize(350,250);
this.setResizable(false);
timeFormat =new SimpleDateFormat("hh:mm:ss a");
dayFormat =new SimpleDateFormat("EEEE");
dateFormat =new SimpleDateFormat("MMMM dd, yyyy");
timeLabel = new JLabel();
timeLabel.setFont(new Font("Roboto",Font.PLAIN,60));
timeLabel.setForeground(new Color(255,102,102));
timeLabel.setBackground(Color.black);
timeLabel.setOpaque(true);
dayLabel = new JLabel();
dayLabel.setFont(new Font("Gill Sans",Font.PLAIN,40));
dateLabel = new JLabel();
dateLabel.setFont(new Font("Gill Sans",Font.PLAIN,30));
this.add(timeLabel);
this.add(dayLabel);
this.add(dateLabel);
this.setVisible(true);
setTime();
}
private void setTime() {
// TODO Auto-generated method stub
while(true) {
time = timeFormat.format(Calendar.getInstance().getTime());
timeLabel.setText(time);
day = dayFormat.format(Calendar.getInstance().getTime());
dayLabel.setText(day);
date = dateFormat.format(Calendar.getInstance().getTime());
dateLabel.setText(date);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new ClockApp();
}
}
Comments (No)