How to create Java Digital clock using Swing
Below java code will create a Digital Java clock using swing components which include JButton, JFrame etc.
import java.awt.Color;
import java.awt.Font;
import java.text.SimpleDateFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.util.Calendar;
import java.util.Date;
import javax.swing.UIManager;
public class JavaDigitalClock extends JFrame implements Runnable{
Thread thread=null;
int hours=0, minutes=0, seconds=0;
String timeString = "";
JButton button;
JavaDigitalClock()
{
super("Java Digital clock Example");
try{
UIManager.setLookAndFeel
("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
}
catch(Exception e){e.printStackTrace();}
button=new JButton();
thread = new Thread(this);
thread.start();
button=new JButton();
button.setBounds(50,50,00,50);
button.setBackground(Color.BLACK);
button.setForeground(Color.WHITE);
button.setFont(new Font("Times New Roman",Font.BOLD,20));
add(button);
setSize(300,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
setVisible(true);
}
@Override
public void run() {
try {
while (true) {
Calendar calendar = Calendar.getInstance();
hours = calendar.get( Calendar.HOUR_OF_DAY );
if ( hours > 12 ) hours -= 12;
minutes = calendar.get( Calendar.MINUTE );
seconds = calendar.get( Calendar.SECOND );
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
Date date = calendar.getTime();
timeString = formatter.format( date );
showTime();
thread.sleep( 1000 ); // interval given in milliseconds }
}
catch (Exception e) { }
}
public void showTime()
{
button.setText(timeString);
}
public static void main(String args[])
{
new JavaDigitalClock();
}
}