Exploring Applet (Part-II)

Discussion in 'Java' started by techgeek.in, Apr 17, 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 first part I discussed about applet fundamentals as to what is an applet, its features, various methods of Applet class and a simple example on applet. In this article I will discuss further on advanced features of applet.

    Applet class



    Applet class provides all necessary support for applet execution, such as starting and stopping. It also provides methods that load and display images, and methods that load and play audio clips. Applet extends the AWT class Panel. In turn, Panel extends Container, which extends Component. These classes provide support for Java’s window-based, graphical interface. Thus, Applet provides all of the necessary support for window-based activities. It provides the following methods:

    void destroy( ) :- Called by the browser just before an applet is terminated. Your applet will override this method if it needs to perform any cleanup prior to its destruction.

    void init( ):- Called when an applet begins execution. It is the first method called for any applet.

    boolean isActive( ):-
    Returns true if the applet has been started. It returns false if the applet has been stopped.

    void start( ):- Called by the browser when an applet should start (or resume) execution. It is automatically called after init( ) when an applet first begins.

    void stop( ):-
    Called by the browser to suspend execution of the applet. Once stopped, an applet is restarted when the browser calls start( ).

    void showStatus(String str):- Displays str in the status window of the browser or applet viewer. If the browser does not support a status window, then no action takes place.

    void resize(int width, int height):-
    Resizes the applet according to the dimensions specified by width and height.

    String getParameter(String paramName):-
    Returns the parameter associated with
    paramName. null is returned if the specified parameter is not found.

    URL getCodeBase( ):- Returns the URL associated with the invoking applet.

    URL getDocumentBase( ):- Returns the URL of the HTML document that invokes the applet.

    AppletContext getAppletContext( ):-
    Returns the context associated with the applet.

    String getAppletInfo( ):- Returns a string that describes the applet.

    In the previous article I discussed about the init( ), start( ), stop( ), and destroy( ) defined by the Applet class and paint( ) defined by the AWT Component class. Here we discuss about another method defined by the AWT, called update( ). In some situations we need to override this method in are applet. This method is called when your applet has requested that a portion of its window be redrawn. The default version of update( ) first fills an applet with the default background color and then calls paint( ). If you fill the background using a different color in paint( ), the user will experience a flash of the default background each time update( ) is called—that is, whenever the window is repainted. One way to avoid this problem is to override the update( ) method so that it performs all necessary display activities. Then have paint( ) simply call update( ).Thus, for some applications, the applet skeleton will override paint( ) and update( ).

    Example:
    Code:
    public void update(Graphics g) 
    {
    // redisplay your window, here.
    }
    public void paint(Graphics g) 
    {
    update(g);
    }
    

    Applet Display Methods



    Applets are displayed in a window and they use the AWT to perform input and output. drawString( ) method which is a member of the Graphics class is used to output a string to an applet. Typically, it is called from within either update( ) or paint( ). It has the following general form:-

    void drawString(String message, int x, int y)

    Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is location 0,0. The drawString( ) method will not recognize newline characters. If you want to start a line of text on another line, you must do so manually, specifying the precise X,Y location where you want the line to begin.

    To set the background color of an applet’s window, use setBackground( ). To set the foreground color i.e the color in which the text is shown use setForeground( ). A good place to set the foreground and background colors is in the init( ) method. The default foreground color is black. The default background color is light gray.

    These methods are defined by Component, and they have the following general forms:

    void setBackground(Color newColor)
    void setForeground(Color newColor)


    Here, newColor specifies the new color. The class Color defines the constants shown that can be used to specify colors:

    Color.black Color.magenta
    Color.blue Color.orange
    Color.cyan Color.pink
    Color.darkGray Color.red
    Color.gray Color.white
    Color.green Color.yellow
    Color.lightGray


    For example, this sets the background color to green and the text color to red:

    setBackground(Color.green);
    setForeground(Color.red);


    We can obtain the current background and foreground colors using the following method:

    Color getBackground( )
    Color getForeground( )

    Here is a very simple applet that sets the background color to cyan, the foreground
    color to red, and displays a message that illustrates the order in which the init( ),
    start( ), and paint( ) methods are called when an applet starts up:

    Code:
    /* A simple applet that sets the foreground and
    background colors and outputs a string. */
    import java.awt.*;
    import java.applet.*;
    /*
    <applet code="Sample" width=300 height=50>
    </applet>
    */
    public class Sample extends Applet{
    	String msg;
    	// set the foreground and background colors.
    	public void init() {
    		setBackground(Color.cyan);
    		setForeground(Color.red);
    		msg = "Inside init( ) --";
    	}
    	// Initialize the string to be displayed.
    	public void start() {
    		msg += " Inside start( ) --";
    	}
    	// Display msg in applet window.
    	public void paint(Graphics g) {
    		msg += " Inside paint( ).";
    		g.drawString(msg, 10, 30);
    	}
    }
    
    This applet generates the window shown here:-

    [​IMG]

    Using the Status Window



    In addition to displaying information in its window, an applet can also output a
    message to the status window of the browser or applet viewer on which it is running.
    To do so, call showStatus( ) with the string that you want displayed. The status window is a good place to give the user feedback about what is occurring in the applet, suggest options, or possibly report some types of errors. The status window also makes an excellent debugging aid, because it gives you an easy way to output information about
    your applet.

    The following applet demonstrates an example of showStatus( ):-
    Code:
    // Using the Status Window.
    import java.awt.*;
    import java.applet.*;
    /*
    <applet code="StatusWindow" width=300 height=50>
    </applet>
    */
    public class StatusWindow extends Applet{
    	public void init() 
    	{
    		setBackground(Color.cyan);
    	}
    	// Display msg in applet window.
    	public void paint(Graphics g) {
    		g.drawString("This is in the applet window.", 10, 20);
    		showStatus("This is shown in the status window.");
    	}
    }
    
    Output from this program is shown here:-
    [​IMG]

    Requesting Repainting



    Generally an applet writes to its window only when its update( ) or paint( ) method is called by the AWT. How can the applet itself cause its window to be updated when its information changes? For example, if an applet is displaying a moving banner, what mechanism does the applet use to update the window each time this banner scrolls? One of the fundamental architectural constraints imposed on an applet is that it must quickly return control to the AWT run-time system. It cannot create a loop inside paint( ) that repeatedly scrolls the banner, for example. This would prevent control from passing back to the AWT.
    Whenever your applet needs to update the information displayed in its window, it simply calls repaint( ). The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a call to your applet’s update( ) method, which, in its default implementation, calls paint( ). Thus, for another part of your applet to output to its window, simply store the output and then call repaint( ). The AWT will then execute a call to paint( ), which can display the stored information.
    The repaint( ) method has four forms. The simplest version of repaint( ) is shown here:

    void repaint( )

    This version causes the entire window to be repainted. The following version specifies a region that will be repainted:

    void repaint(int left, int top, int width, int height)


    Here, the coordinates of the upper-left corner of the region are specified by left and top, and the width and height of the region are passed in width and height. These dimensions are specified in pixels. You save time by specifying a region to repaint. Calling repaint( ) is essentially a request that your applet be repainted sometime soon. However, if your system is slow or busy, update( ) might not be called immediately. This can be a problem in many situations, including animation, in which a consistent update time is necessary. One solution to this problem is to use the following forms of repaint( ):

    void repaint(long maxDelay)
    void repaint(long maxDelay, int x, int y, int width, int height)


    Here, maxDelay specifies the maximum number of milliseconds that can elapse before update( ) is called.

    To demonstrate repaint( ), a simple banner applet is developed. This applet scrolls a message, from right to left, across the applet’s window. Since the scrolling of the message is a repetitive task, it is performed by a separate thread, created by the applet when it is initialized.
    Code:
    /* A simple banner applet.
    */
    import java.awt.*;
    import java.applet.*;
    /*
    <applet code="SimpleBanner" width=300 height=50>
    </applet>
    */
    
    public class SimpleBanner 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);
    	}
    }
    

    Must Read Concept Of Paint(), update() and repaint()



    Both paint() and update() are called by AWT sending Graphics object as an argument. If update() is overridden then the paint() method should also be overridden. update() always calls paint().

    public void update(Graphics g) and public void paint(graphics g) are the prototypes of the update() and paint() methods. repaint() is not different form update(). But repaint() does not have any parameter and hence Graphics context is not known while using repaint(). repaint() is mainly used in methods where Graphics context is not known. There is no need of using repaint() if Graphics context can be obtained by using the method getGraphics() in the Component class by using following line:-

    Graphics g1=this.getGraphics();

    Now, using update() or repaint() simultaneously with the paint() in the applet class without creating thread may cause the applet to take the full control of the program and no control is being transferred to AWT. Hence, the applet window cannot be closed.

    Example 1:-

    Code:
    class NewApplet extends Applet
    {
    	public void paint(Graphics g)
    	{
    		msg+="a";
    		g.drawstring(msg,50,50);
    		try
    		{
    			Thread.sleep(1000);
    		}catch(EXception e){};
    		update(g);
    	}
    	public void update(Graphics g)
    	{ 
    		paint(g);
    	}
    }  
    

    Example 2:-

    Code:
    class NewApplet extends Applet
    {
    	public void paint(Graphics g)
    	{
    		msg+="a";
    		g.drawstring(msg,50,50);
    		try
    		{
    			Thread.sleep(1000);
    		}catch(EXception e){};
    		repaint();
    	}
    }
    
    The above examples clearly represent that how the applet can be responsible for talking the full control.

    For scrolling banner example instead of repaint() we could have written the following two line:-

    Graphics g=this.getGraphics();
    update(g);

    Only a Thread can prevent from going into infinite loop. Window cannot be closed in case applet goes into an infinite loop.

    HTML APPLET Tag



    The APPLET tag is used to start an applet from both an HTML document and from an applet viewer. An applet viewer will execute each APPLET tag that it finds in a separate window, while web browsers like Netscape Navigator, Internet Explorer etc will allow many applets on a single page. In the last article I discussed a simplified form of the APPLET tag. Here we take a closer look at it.

    The syntax for the standard APPLET tag is shown here. Bracketed items
    are optional.
    < APPLET
    [CODEBASE = codebaseURL]
    CODE = appletFile
    [ALT = alternateText]
    [NAME = appletInstanceName]
    WIDTH = pixels HEIGHT = pixels
    [ALIGN = alignment]
    [VSPACE = pixels] [HSPACE = pixels]
    >
    [< PARAM NAME = AttributeName VALUE = AttributeValue>]
    [< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
    . . .
    [HTML Displayed in the absence of Java]
    </APPLET>

    CODEBASE:-CODEBASE is an optional attribute that specifies the base URL of the applet code, which is the directory that will be searched for the applet’s executable class file.

    CODE:-
    CODE is a required attribute that gives the name of the file containing your applet’s compiled .class file.

    ALT:- The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser understands the APPLET tag but can’t currently run Java applets.

    NAME:- NAME is an optional attribute used to specify a name for the applet instance.

    WIDTH AND HEIGHT:- WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area.

    ALIGN:- ALIGN is an optional attribute that specifies the alignment of the applet.
    This attribute is treated the same as the HTML IMG tag with these possible values:
    LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.

    VSPACE AND HSPACE:- These attributes are optional. VSPACE specifies the space, in pixels, above and below the applet. HSPACE specifies the space, in pixels, on each side of the applet.

    PARAM NAME AND VALUE:- The PARAM tag allows you to specify appletspecific arguments in an HTML page. Applets access their attributes with the
    getParameter( ) method.

    Passing Parameters to Applets



    As discussed above the APPLET tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use the getParameter( ) method. It returns the value of the specified parameter in the form of a String object. Thus, for numeric and Boolean values, you will need to convert their string representations into their internal formats.

    Here is an example that demonstrates passing parameters:
    Code:
    // Use Parameters
    
    import java.awt.*;
    import java.applet.*;
    
    /*
    <applet code="ParamDemo" width=300 height=80>
    <param name=fontName value=Courier>
    <param name=fontSize value=14>
    <param name=leading value=2>
    <param name=accountEnabled value=true>
    </applet>
    */
    
    public class ParamDemo extends Applet{
    
    	String fontName;
    	int fontSize;
    	float leading;
    	boolean active;
    
    	// Initialize the string to be displayed.
    
    	public void start() {
    		String param;
    		fontName = getParameter("fontName");
    		if(fontName == null)
    			fontName = "Not Found";
    		param = getParameter("fontSize");
    		try {
    			if(param != null)    // if not found
    				fontSize = Integer.parseInt(param);
    			else
    				fontSize = 0;
    		}
    		catch(NumberFormatException e) {
    			fontSize = -1;
    		}
    		param = getParameter("leading");
    		try {
    			if(param != null) // if not found
    				leading = Float.valueOf(param).floatValue();
    			else
    				leading = 0;
    		}
    		catch(NumberFormatException e) {
    			leading = -1;
    		}
    		param = getParameter("accountEnabled");
    		if(param != null)
    			active = Boolean.valueOf(param).booleanValue();
    	}
    	// Display parameters.
    	public void paint(Graphics g) {
    		g.drawString("Font name: " + fontName, 0, 10);
    		g.drawString("Font size: " + fontSize, 0, 26);
    		g.drawString("Leading: " + leading, 0, 42);
    		g.drawString("Account Active: " + active, 0, 58);
    	}
    }
    
    output:-

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

    shabbir Administrator Staff Member

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

    TPrice New Member

    Joined:
    Aug 24, 2010
    Messages:
    9
    Likes Received:
    1
    Trophy Points:
    0
    This is a great article on exploring the applet. This is something I have been trying to wrap my head around, and you have offered me some clarity on this. I actually feel that I have some level of comprehension here, which is more than I had before I read this. Thank you very much for sharing this valuable information!
     

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