Friday 24 March 2017

Passing Parameters to Applets, getDocumentBase( ) and getCodeBase( ) & AppletContext and showDocument( ) - Java Tutorials

Passing Parameters to Applets

As just discussed, 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:

  // 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);
    }
  }

As the program shows, you should test the return values from getParameter( ). If a parameter isn’t available, getParameter( ) will return null. Also, conversions to numeric types must be attempted in a try statement that catches NumberFormatException. Uncaught exceptions should never occur within an applet.


Improving the Banner Applet

It is possible to use a parameter to enhance the banner applet shown earlier. In the previous version, the message being scrolled was hard-coded into the applet. However, passing the message as a parameter allows the banner applet to display a different message each time it is executed. This improved version is shown here. Notice that the APPLET tag at the top of the file now specifies a parameter called message that is linked to a quoted string.

  // A parameterized banner
  import java.awt.*;
  import java.applet.*;
  /*
  <applet code="ParamBanner" width=300 height=50>
  <param name=message value="Java makes the Web move!">
  </applet>
  */

  public class ParamBanner extends Applet implements Runnable {
    String msg;
    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() {
      msg = getParameter("message");
      if(msg == null) msg = "Message not found.";
      msg = " " + msg;
      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);
    }
  }




getDocumentBase( ) and getCodeBase( )

Often, you will create applets that will need to explicitly load media and text. Java will allow the applet to load data from the directory holding the HTML file that started the applet (the document base) and the directory from which the applet’s class file was loaded (the code base). These directories are returned as URL objects (described in Chapter 18) by getDocumentBase( ) and getCodeBase( ). They can be concatenated with a string that names the file you want to load. To actually load another file, you will use the showDocument( ) method defined by the AppletContext interface, discussed in the next section.

The following applet illustrates these methods:

  // Display code and document bases.
  import java.awt.*;
  import java.applet.*;
  import java.net.*;
  /*
  <applet code="Bases" width=300 height=50>
  </applet>
  */

  public class Bases extends Applet{
    // Display code and document bases.
    public void paint(Graphics g) {
      String msg;

      URL url = getCodeBase(); // get code base
      msg = "Code base: " + url.toString();
      g.drawString(msg, 10, 20);

      url = getDocumentBase(); // get document base
      msg = "Document base: " + url.toString();
      g.drawString(msg, 10, 40);
    }
  }




AppletContext and showDocument( )

One application of Java is to use active images and animation to provide a graphical means of navigating the Web that is more interesting than the underlined blue words used by hypertext. To allow your applet to transfer control to another URL, you must use the showDocument( ) method defined by the AppletContext interface. AppletContext is an interface that lets you get information from the applet’s execution environment. The methods defined by AppletContext are shown in Table 19-2. The context of the currently executing applet is obtained by a call to the getAppletContext( ) method defined by Applet.

Within an applet, once you have obtained the applet’s context, you can bring another document into view by calling showDocument( ). This method has no return value and throws no exception if it fails, so use it carefully. There are two showDocument( ) methods. The method showDocument(URL) displays the document at the specified URL. The method showDocument(URL, where) displays the specified document at the specified location within the browser window. Valid arguments for where are “_self” (show in current frame), “_parent” (show in parent frame), “_top” (show in topmost frame), and “_blank” (show in new browser window). You can also specify a name, which causes the document to be shown in a new browser window by that name.


The Abstract Methods Defined by the AppletContext Interface

Applet getApplet(String appletName):  Returns the applet specified by appletName if it is within the current applet context. Otherwise, null is returned.

Enumeration getApplets( ):  Returns an enumeration that contains all of the applets within the current applet context.

AudioClip getAudioClip(URL url):  Returns an AudioClip object that encapsulates the audio clip found at the location specified by url.

Image getImage(URL url):  Returns an Image object that encapsulates the image found at the location specified by url.

InputStream getStream(String key):  Returns the stream linked to key. Keys are linked to streams by using the setStream( ) method. A null reference is returned if no stream is linked to key. (Added by Java 2, version 1.4)

Iterator getStreamKeys( ):  Returns an iterator for the keys associated with the invoking object. The keys are linked to streams. See getStream( ) and setStream( ). (Added by Java 2, version 1.4)

void setStream(String key, InputStream strm):  Links the stream specified by strm to the key passed in key. The key is deleted from the invoking object if strm is null. (Added by Java 2, version 1.4)

void showDocument(URL url):  Brings the document at the URL specified by url into view. This method may not be supported by applet viewers.

void showDocument(URL url, String where):  Brings the document at the URL specified by url into view. This method may not be supported by applet viewers. The placement of the document is specified by where as described in the text.

void showStatus(String str):  Displays str in the status window.


The following applet demonstrates AppletContext and showDocument( ). Upon execution, it obtains the current applet context and uses that context to transfer control to a file called Test.html. This file must be in the same directory as the applet. Test.html can contain any valid hypertext that you like.

  /* Using an applet context, getCodeBase(),
     and showDocument() to display an HTML file.
  */

  import java.awt.*;
  import java.applet.*;
  import java.net.*;
  /*
  <applet code="ACDemo" width=300 height=50>
  </applet>
  */

  public class ACDemo extends Applet{
    public void start() {
      AppletContext ac = getAppletContext();
      URL url = getCodeBase(); // get url of this applet

      try {
        ac.showDocument(new URL(url+"Test.html"));
      } catch(MalformedURLException e) {
        showStatus("URL not found");
      }
    }
  }


The AudioClip Interface

The AudioClip interface defines these methods: play( ) (play a clip from the beginning), stop( ) (stop playing the clip), and loop( ) (play the loop continuously). After you have loaded an audio clip using getAudioClip( ), you can use these methods to play it.


The AppletStub Interface

The AppletStub interface provides the means by which an applet and the browser (or applet viewer) communicate. Your code will not typically implement this interface.


Outputting to the Console

Although output to an applet’s window must be accomplished through AWT methods, such as drawString( ), it is still possible to use console output in your applet—especially for debugging purposes. In an applet, when you call a method such as System.out.println( ), the output is not sent to your applet’s window. Instead, it appears either in the console session in which you launched the applet viewer or in the Java console that is available in some browsers. Use of console output for purposes other than debugging is discouraged, since it violates the design principles of the graphical interface most users will expect.

No comments:

Post a Comment