Digital Clock
Hey there!
Time is precious. Time and tide wait for none. Time is money. It is true that most valuable thing in our lives is time. Time once gone cannot come back. So , this is a small and simple project exhibiting how to make a digital clock in java using Applets.
The code for the entire project is as follows :
import java.util.*; import java.applet.*; import java.awt.*; import javax.swing.JOptionPane; public class txt extends Applet { public void init() { resize(800, 600); setBackground(Color.orange); } public void paint(Graphics g) { //font for 'DIGITAL CLOCK' heading Font name = new Font("Arial", Font.PLAIN, 20); Font f = new Font("Verdana", Font.BOLD, 70); //Getting values of hours, minutes and seconds Scanner s = new Scanner(System.in); int h = s.nextInt(); int m = s.nextInt(); int sec = s.nextInt(); g.setFont(name); g.setColor(Color.black); g.drawString("DIGITAL CLOCK", 200, 300); g.setColor(Color.gray); //Outer body of clock g.fillRect(70, 70, 460, 160); if (h > 11 || m > 59 || sec > 59) { JOptionPane.showMessageDialog(this, "Invalid Input"); } else { g.setFont(f); String hour, min, seconds; try { while (true) { while (h < 12) { while (m < 60) { while (sec < 60) { g.setColor(Color.green); hour = Integer.toString(h); min = Integer.toString(m); seconds = Integer.toString(sec); if (h < 10) { g.drawString("0" + hour, 110, 170); } if (h > 9) { g.drawString(hour, 110, 170); } if (m < 10) { g.drawString("0" + min, 250, 170); } if (m > 9) { g.drawString(min, 250, 170); } if (sec < 10) { g.drawString("0" + seconds, 390, 170); } if (sec > 9) { g.drawString(seconds, 390, 170); } g.drawString(":", 210, 170); g.drawString(":", 350, 170); Thread.sleep(1000); g.setColor(Color.black); g.fillRect(100, 100, 400, 100); sec++; } m++; sec = 0; } h++; m = 0; } h = 0; } } catch (Exception e) { } } } }
We get the value of time from the user in the format: hours minutes seconds using the Scanner.
//Getting values of hours, minutes and seconds Scanner s = new Scanner(System.in); int h = s.nextInt(); int m = s.nextInt(); int sec = s.nextInt();
After the input the clock starts running .
The font used for the clock is “Verdana”, you can use any different font of your choice. Additional modifications can be done to make it more pleasing and also additional features can be added like alarm , stopwatch etc.
It is a very helpful program for beginners as it thoroughly makes use of thread, applet, graphics in one single project.
Do try it out.
Vijay Kashyap
Latest posts by Vijay Kashyap (see all)
- Digital Clock - November 19, 2017
- HELLO WORLD Animation - November 16, 2017
- How to make a bouncing ball animation in java - November 7, 2017