Friday, 1 May 2015

Digital clock in Applet

Digital clock in Applet

Digital clock can be created by using the Calendar and SimpleDateFormat class. Let's see the simple example:
Example of Digital clock in Applet:

1.    import java.applet.*;  
2.    import java.awt.*;  
3.    import java.util.*;  
4.    import java.text.*;  
5.      
6.    public class DigitalClock extends Applet implements Runnable {  
7.      
8.       Thread t = null;  
9.       int hours=0, minutes=0, seconds=0;  
10.    String timeString = "";  
11.   
12.    public void init() {  
13.       setBackground( Color.green);  
14.    }  
15.   
16.    public void start() {  
17.         t = new Thread( this );  
18.         t.start();  
19.    }  
20.   
21.     
22.    public void run() {  
23.       try {  
24.          while (true) {  
25.   
26.             Calendar cal = Calendar.getInstance();  
27.             hours = cal.get( Calendar.HOUR_OF_DAY );  
28.             if ( hours > 12 ) hours -= 12;  
29.             minutes = cal.get( Calendar.MINUTE );  
30.             seconds = cal.get( Calendar.SECOND );  
31.   
32.             SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");  
33.             Date date = cal.getTime();  
34.             timeString = formatter.format( date );  
35.   
36.             repaint();  
37.             t.sleep( 1000 );  // interval given in milliseconds  
38.          }  
39.       }  
40.       catch (Exception e) { }  
41.    }  
42.   
43.     
44.   public void paint( Graphics g ) {  
45.       g.setColor( Color.blue );  
46.       g.drawString( timeString, 5050 );  
47.    }  
48. }  
In the above example, getX() and getY() method of MouseEvent is used to get the current x-axis and y-axis. The getGraphics() method of Component class returns the object of Graphics.

myapplet.html

1.    <html>  
2.    <body>  
3.    <applet code="DigitalClock.class" width="300" height="300">  
4.    </applet>  
5.    </body>  

6.    </html>  

No comments:

Post a Comment

Access attributes in component

NOTE: To access an attribute in a  component , use expressions as  {! v.<Attribute Name>} . ----------------------------------------...