Example of digital
clock in swing:
1. import javax.swing.*;
2. import java.awt.*;
3. import java.text.*;
4. import java.util.*;
5. public class DigitalWatch implements Runnable{
6. JFrame f;
7. Thread t=null;
8. int hours=0, minutes=0, seconds=0;
9. String timeString = "";
10. JButton b;
11.
12. DigitalWatch(){
13. f=new JFrame();
14.
15. t = new Thread(this);
16. t.start();
17.
18. b=new JButton();
19. b.setBounds(100,100,100,50);
20.
21. f.add(b);
22. f.setSize(300,400);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26.
27. public void run() {
28. try {
29. while (true) {
30.
31. Calendar cal = Calendar.getInstance();
32. hours = cal.get( Calendar.HOUR_OF_DAY );
33. if ( hours > 12 ) hours -= 12;
34. minutes = cal.get( Calendar.MINUTE );
35. seconds = cal.get( Calendar.SECOND );
36.
37. SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
38. Date date = cal.getTime();
39. timeString = formatter.format( date );
40.
41. printTime();
42.
43. t.sleep( 1000 ); // interval given in milliseconds
44. }
45. }
46. catch (Exception e) { }
47. }
48.
49. public void printTime(){
50. b.setText(timeString);
51. }
52.
53. public static void main(String[] args) {
54. new DigitalWatch();
55.
56.
57. }
58. }
No comments:
Post a Comment