Applet Examples (Part-III)

Discussion in 'Java' started by techgeek.in, Apr 18, 2010.

  1. techgeek.in

    techgeek.in New Member

    Joined:
    Dec 20, 2009
    Messages:
    572
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    EOC (exploitation of computers)..i m a Terminator.
    Location:
    Not an alien!! for sure
    Home Page:
    http://www.techgeek.in
    In the previous two articles I discussed all essential features and methods of applet. Here I give some examples which would clear your concept about applets.

    A Font List Example



    This is an example of an applet that displays the standard fonts and styles.

    Code:
    import java.applet.*;
    import java.awt.*;
    
    /*
    <applet code="FontList" width=300 height=500>
    </applet>
    */
    public class FontList extends Applet
    {
    	// The available font families
    	String[] families = {"Serif",          
    			   "SansSerif",      
    			   "Monospaced",    
    			   "Dialog",        
    			   "DialogInput" }; 
    
    	// The available font styles
    
    	int[] styles = {Font.PLAIN, Font.ITALIC, Font.BOLD, Font.ITALIC+Font.BOLD};
    	String[] stylenames = {"Plain", "Italic", "Bold", "Bold Italic"};
    
    	public void paint(Graphics g) 
    	{
    		for(int family=0; family < families.length; family++) 
    		{        
    			// for each family
    			for(int style = 0; style < styles.length; style++) 
    			{              
    				// for each style
    				Font f = new Font(families[family], styles[style], 16);  
    				// create font
    				String s = families[family] + " " + stylenames[style];  
    				// create name
    				g.setFont(f);                                                                 
    				// set font
    				g.drawString(s, 10, (family*4 + style + 1) * 20);      
    				// display name
    			}
    		 }
    	}
    }
    
    
    Output is show here:-

    [​IMG]

    A Simple Timer Applet



    In this program we implement a timer using Applet class. This applet also implements Runnable. This is necessary, since the applet will be creating a second thread of execution that will be used to update the time every second. Inside init( ), the foreground and background colors of the applet are set. After initialization, the AWT run-time system calls start( ) to start the applet running. Inside start( ), a new thread of execution is created and assigned to the Thread variable clock. Then, the boolean variable value, which controls the execution of the applet, is set to false. Next, the thread is started by a call to t.start( ). t.start( ) calls a method defined by Thread class, which causes run( ) to begin executing. It does not cause a call to the version of start( ) defined by Applet. These are two separate methods.

    Inside run( ), the time is updated is every second. Between each updation, a call to repaint( ) is made. This eventually causes the paint( ) method to be called and the current time in hours , minutes and seconds is displayed. Between each iteration, run( ) sleeps for a quarter of a second. The net effect of run( ) is that the time in hours , minutes and seconds is displayed each second.

    If a browser is displaying the applet when a new page is viewed, the stop( ) method is called, which sets value to true, causing run( ) to terminate. This is the mechanism used to stop the thread when its page is no longer in view. When the applet is brought back into view, start( ) is once again called, which starts a new thread to execute the timer.

    Code:
    import java.awt.*;
    import java.applet.*;
    /*
    <applet code="timer" width=300 height=200>
    </applet>
    */
    public class timer extends Applet implements Runnable
    {
    	Thread clock=null;
    	boolean value;
    	private String msg=new String("");
    	private int hrs;
    	private int secs;
    	private int mins;
    	public void init()
    	{
    		setBackground(Color.cyan);
    		setForeground(Color.red);
    	}
    
    	public void start()
    	{
    		clock=new Thread(this);
    		value=false;
    		clock.start();
    	}
    
    	public void run()
    	{
    		for(;;)
    		{
    			try
    			{
    				repaint();
    				clock.sleep(1000);
    			}catch(InterruptedException e){}
    		}
    	}
    
    	public void stop()
    	{
    		value=true;
    		clock=null;
    	}
    
    	public void paint(Graphics g)
    	{
    		secs++;
    		if(secs==60)
    		{
    			mins++;
    			secs=0;
    
    		}
    
    		if(mins==60)
    		{
    			hrs++;
    			secs=0;
    			mins=0;
    		}
    		g.setColor(Color.black);
    		g.drawString(" "+hrs+" Hours "+mins+" Minutes "+secs+" Seconds ",10,130);
    	}
    }
    
    
    
    The output is shown here:-

    [​IMG]

    A Simple Banner Applet



    Banner extends Applet and implements Runnable. This is necessary, since the applet will be creating a second thread of execution that will scroll the banner. Inside init( ), the foreground and background colors of the applet are set.

    After initialization, the AWT run-time system calls start( ) to start the applet running. Inside start( ), a new thread of execution is created and assigned to the Thread variable t. Then, the boolean variable stopFlag, which controls the execution of the applet, is set to false. Next, the thread is started by a call to t.start( ). t.start( ) calls a method defined by Thread, which causes run( ) to begin executing. It does not cause a call to the version of start( ) defined by Applet. These are two separate methods.Inside run( ), the characters in the string contained in msg are repeatedly rotated left. Between each rotation, a call to repaint( ) is made. This eventually causes the paint( ) method to be called and the current contents of msg is displayed. Between each iteration, run( ) sleeps for a quarter of a second. The net effect of run( ) is that the contents of msg is scrolled right to left in a constantly moving display. The stopFlag variable is checked on each iteration. When it is true, the run( ) method terminates. If a browser is displaying the applet when a new page is viewed, the stop( ) method is called, which sets stopFlag to true, causing run( ) to terminate. This is the mechanism used to stop the thread when its page is no longer in view. When the applet is brought back into view, start( ) is once again called, which starts a new thread to execute the banner.

    Code:
    import java.awt.*;
    import java.applet.*;
    /*
    <applet code="banner" width=300 height=50>
    </applet>
    */
    public class banner extends Applet implements Runnable 
    {
    	String msg = "A Simple Moving Banner.";
    	Thread t = null;
    	int state;
    	boolean stopFlag;
    
    	// Set colors and initialize thread.
    
    	public void init() 
    	{
    		setBackground(Color.cyan);
    		setForeground(Color.red);
    	}
    
    	// Start thread
    
    	public void start() 
    	{
    		t = new Thread(this);
    		stopFlag = false;
    		t.start();
    	}
    
    	// Entry point for the thread that runs the banner.
    
    	public void run() 
    	{
    		char ch;
    		// Display banner
    		for( ; ; ) 
    		{
    			try 
    			{
    				repaint();
    				Thread.sleep(250);
    				ch = msg.charAt(0);
    				msg = msg.substring(1, msg.length());
    				msg += ch;
    				if(stopFlag)
    					break;
    			} catch(InterruptedException e) {}
    		}
    	}
    
    	// Pause the banner.
    
    	public void stop() 
    	{
    		stopFlag = true;
    		t = null;
    	}
    
    	// Display the banner.
    
    	public void paint(Graphics g) 
    	{
    		g.drawString(msg, 50, 30);
    	}
    }
    
    
    Following is the output:-

    [​IMG]

    A Bouncing Ball example


    In the following example class bounce extends Applet and implements Runnable. Runnable is implemented to create a thread which will help in changing the position of the ball and hence check for the boundary conditions of the applet window. If the boundary conditions are met the ball is traced in opposite path else the ball proceeds. The change in position is drawn by paint() by continuous calling of repaint().

    Code:
    import java.applet.*;
    import java.awt.*;
    /*
    <applet code="bounce" width=200 height=200>
    </applet>
    */
    
    public class bounce extends Applet implements Runnable 
    {
    	int x = 150, y = 50, r=20;    // position and radius of the circle
    	int dx = 11, dy = 7;          // trajectory of circle
    	Thread t;
    	boolean stopFlag;
    
    	public void start() 
    	{
    		t = new Thread(this);
    		stopFlag=false; 
    		t.start();
    	}
    
    	/*Draw the circle at its current position */
    
    	public void paint(Graphics g) 
    	{
    		g.setColor(Color.red);
    		g.fillOval(x-r, y-r, r*2, r*2);
    	}
    
    
    	public void run() 
    	{
    		while(true)
    		{
    			if(stopFlag)
    				break;
    			// Bounce if we've hit an edge.
    			if ((x - r + dx < 0) || (x + r + dx > bounds().width)) dx = -dx;
    			if ((y - r + dy < 0) || (y + r + dy > bounds().height)) dy = -dy;
    			// Move the circle.
    			x += dx;  y += dy;
    
    			try
    			{
    				Thread.sleep(100);
    			}catch(Exception e){};
    			// Ask the browser to call our paint() method to draw the circle
    			// at its new position.
    			repaint();
    		}
    	}
    
    	public void stop()
    	{
    		stopFlag=true;
    		t=null;
    	}
    }
    
    The output is the following:-

    [​IMG]

    A Patterned Circle Example



    We have tried a different types of pattern making in console based programs. But an Applet can give a nice graphical pattern using circles. The following code try to make pattern using black and white balls. To change the number of rows and columns change the limit of i and j i.e change the number 3 to the desired number.

    Code:
    import java.applet.*;
    import java.awt.*;
    
    /* <applet code="pattern" height=200 width=300>
     </applet>
     */
    
    /*
    A Special Note:
    While specifying an oval we have to pass the top-left corner (x,y) co-ordinates of the 
    bounding box and the height and width of the bounding box
    A bounding box is defined as the smallest rectangle which can completely contain the oval
    If the height and width is same then a circle is drawn
    */
     
    public class pattern extends Applet
    {
    	public void paint(Graphics g)
    	{
    		int i,j;
    		for(i=0;i<3;i++)	// Three rows
    		{
    			for(j=0;j<3;j++)		//Three columns
    			{
    				if((i+j)%2==0)					
    					//if sum of i and j is even then draw empty circle else draw filled in circle
    					g.drawOval(i*60,j*60,30,30);
    				else
    					g.fillOval(i*60,j*60,30,30);
    			}
    		}
    	}
    }
    
    Output:-
    [​IMG]

    Concentric Circle Example


    Code:
    import java.applet.*;
    import java.awt.*;
    /*<applet code="ConcCircles" height=250 width=300>
      </applet>
     */
    
    /*
    A Special Note:
    While specifying an oval we have to pass the top-left corner (x,y) co-ordinates of the bounding box and the height and width of the bounding box
    A bounding box is defined as the smallest rectangle which can completely contain the oval
    If the height and width is same then a circle is drawn
    */
     
    public class ConcCircles extends Applet
    {
    	public void paint(Graphics g)
    	{
    		g.setColor(Color.RED);			//Set the colour to red
    		g.drawOval(50,50,150,150);		// Refer to special note above for explanation of parameters
    		g.setColor(Color.BLUE);			// Set the colour to blue
    		g.drawOval(75,75,100,100);		// 100 pixel diameter circle is drawn
    		g.setColor(Color.GREEN);		//Set the colour to green
    		g.drawOval(100,100,50,50);
    	}
    }
    
    
    Output:-

    [​IMG]

    A Simple Image Applet



    This example illustrates how to display images in an applet. MediaTracker is a utility class of java.awt.* package that tracks the status of a number of media objects. This type of object can also include images and audio clips. The addImage() method of the MediaTracker class is used after creating an instance of this class. The getImage() method is used to return the image for the object ( img ) of the Image class taking two arguments, first is getCodeBase() and another is image name. Syntax of the addImage() function is
    MediaTracker.addImage(img, x, y, x1, y1).
    Arguments are :
    img - image name type of Image.
    x - lower X - Coordinate type of int.
    y - lower Y - Coordinate type of int.
    x1 - upper X - Coordinate type of int.
    y1 - upper Y - Coordinate type of int.

    Code:
    import java.applet.*;
    import java.awt.*;
    /*<applet code="Image" height=300 width=300>
      </applet>
     */
    
    
     
    public class Image extends Applet
    {
    	Image img;
    	MediaTracker tr;
    	public void paint(Graphics g) 
    	{
    		tr = new MediaTracker(this);
    		img = getImage(getCodeBase(),"water.gif");
    		tr.addImage(img,0);
    		g.drawImage(img, 0, 0, this);
    	} 
    }
    //water.gif is kept in the same place where the .java file exists.
    
    Output:-
    [​IMG]

    A simple Line Animation Example



    This applet implements Runnable as it creates a separate stream of execution, to perform a background task. The body of the thread's code is in the run() function which is executed after called start() method. In this case, the purpose of the thread is to increment the variable i once every 1000 milliseconds, and cause the applet to redraw itself. The result is a simple animation.

    Code:
    import java.applet.*;
    import java.awt.*;
    
    /*
     <applet code="Threads1" width="500" height="500">
     </applet>
     */
    
    public class Threads1 extends Applet implements Runnable 
    {
    	int width, height;
    	int i = 0;
    	Thread t = null;
    	boolean threadSuspended;
    
    	public void init() 
    	{
    		//System.out.println("init(): begin");
    		width = getSize().width;
    		height = getSize().height;
    		setBackground( Color.black );
    		// System.out.println("init(): end");
    	}
    
    	public void destroy() 
    	{
    		//System.out.println("destroy()");
    	}
    
    	public void start() 
    	{
    		//System.out.println("start(): begin");
    		if ( t == null ) 
    		{
    			//System.out.println("start(): creating thread");
    			t = new Thread( this );
    			//System.out.println("start(): starting thread");
    			threadSuspended = false;
    			t.start();
    		}
    		else 
    		{
    			if ( threadSuspended ) 
    			{
    				threadSuspended = false;
    				//System.out.println("start(): notifying thread");
    				synchronized( this ) 
    				{
    					notify();
    				}
    			}
    		}
    		//System.out.println("start(): end");
    	}
    
    	public void stop() 
    	{
    		//System.out.println("stop(): begin");
    		threadSuspended = true;
    	}
    
    	public void run() 
    	{
    		// System.out.println("run(): begin");
    		try 
    		{
    			while (true) 
    			{
    				// System.out.println("run(): awake");
    
    				// Here's where the thread does some work
    				++i;  
    				if ( i == 10 ) 
    				{
    					i = 0;
    				}
    				showStatus( "i is " + i );
    
    				// Now the thread checks to see if it should suspend itself
    				if ( threadSuspended ) 
    				{
    					synchronized( this ) 
    					{
    						while ( threadSuspended ) 
    						{
    							//System.out.println("run(): waiting");
    							wait();
    						}
    					}
    				}
    				//System.out.println("run(): requesting repaint");
    				repaint();
    				//System.out.println("run(): sleeping");
    				t.sleep( 1000 );  // interval given in milliseconds
    			}
    		}catch (InterruptedException e) { }
    		//System.out.println("run(): end");
    	}
    
    	// Executed whenever the applet is asked to redraw itself.
    
    	public void paint( Graphics g ) 
    	{
    		//System.out.println("paint()");
    		g.setColor( Color.green );
    		g.drawLine( width, height, i * width / 10, 0 );
    	}
    }
    
    Output:-

    [​IMG]
     
    Last edited by a moderator: Jan 21, 2017
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice