Created
July 9, 2018 21:34
-
-
Save atechcrew/82a11ad33106fcf8b1b21ed99f6a76aa to your computer and use it in GitHub Desktop.
Real time digital clock in java. Digital clock using java. Java code to make real time digital clock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.Font; | |
import java.text.DecimalFormat; | |
import javax.swing.JFrame; | |
import javax.swing.JLabel; | |
public class LiveDigitalClock { | |
public static JLabel label; | |
public static int hours = 00, minutes = 00, seconds = 00; | |
public static void ticking(){ | |
seconds++; | |
if(seconds >= 60){ | |
minutes++; | |
seconds = 00; | |
if(minutes >= 60){ | |
hours++; | |
minutes = 00; | |
if(hours >= 24){ | |
hours = 00; | |
} | |
} | |
} | |
} | |
public static void main(String args[]) { | |
Runnable run = new Runnable() { | |
@Override | |
public void run() { | |
try { | |
displayClock(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
}; | |
Thread thread = new Thread(run); | |
thread.start(); | |
} | |
public static void startClock() throws Exception{ | |
while(true) { | |
ticking(); | |
String time = clockFormat(hours, minutes, seconds); | |
label.setText(time); | |
Thread.sleep(999); | |
} | |
} | |
public static String clockFormat(int hours, int minutes, int seconds) { | |
DecimalFormat formatter = new DecimalFormat("00"); | |
return formatter.format(hours) + ":" + formatter.format(minutes) + ":" + formatter.format(seconds); | |
} | |
public static void displayClock() throws Exception{ | |
JFrame frame = new JFrame(); | |
frame.setTitle("Java Clock"); | |
frame.setBounds(500, 300, 258, 110); | |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
frame.getContentPane().setLayout(null); | |
label = new JLabel("00:00:00"); | |
label.setFont(new Font(label.getFont().getName(), Font.PLAIN, 60)); | |
label.setBounds(5, 3, 250, 60); | |
frame.getContentPane().add(label); | |
frame.setVisible(true); | |
startClock(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment