Applications, applets, and hybrids

Java 101 charts a new course, and explores applications, applets, and hybrids

1 2 3 Page 3
Page 3 of 3
// Hybrid.java
// To run applet under Netscape Communicator 4.7 browser or Internet
// Explorer 5.0 internal JVM, compile using javac -target 1.1 Hybrid.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Hybrid extends Applet implements ActionListener
{
   static Hybrid h;
   static Stub s;
   Image im;
   public void init ()
   {
      System.out.println ("init () called");
      System.out.println ("isActive () returns " + isActive ());
      // Create simple GUI.
      Button b = new Button ("Visit Javasoft");
      b.addActionListener (this);
      add (b);
      b = new Button ("Giggle");
      b.addActionListener (this);
      add (b);
      // Obtain an Image object in preparation for loading.
      String imageName = getParameter ("image");
      im = getImage (getCodeBase (), imageName);
   }
   public void start ()
   {
      System.out.println ("start () called");
      System.out.println ("isActive () returns " + isActive ());
   }
   public void paint (Graphics g)
   {
      // Load and draw an image.
      if (im != null)
          g.drawImage (im, 0, 0, this);
   }
   public void actionPerformed (ActionEvent e)
   {
      if (e.getActionCommand ().equals ("Giggle"))
      {
          String soundName = getParameter ("sound");
          if (soundName != null)
          {
              AudioClip ac = getAudioClip (getDocumentBase (),
                                           soundName);
              ac.play ();
          }
          return;
      }
      try
      {
          URL u = new URL ("http://www.javasoft.com");
          getAppletContext ().showDocument (u);
      }
      catch (MalformedURLException exc) { System.out.println (e); }
   }
   public void stop ()
   {
      System.out.println ("stop () called");
      System.out.println ("isActive () returns " + isActive ());
   }
   public void destroy ()
   {
      System.out.println ("destroy () called");
      System.out.println ("isActive () returns " + isActive ());
   }
   public static void main (String [] args)
   {
      Frame frame = new Frame ("Hybrid as an Application");
      h = new Hybrid ();
      frame.add (new Panel ().add (h));
      // Create the frame's peer.  Peer is not visible.
      frame.addNotify ();
      h.setStub (s = new Stub (args));
      h.init ();
      frame.setSize (300, 200);
      frame.setVisible (true);
      s.setActive (true);
      h.start ();
      frame.addWindowListener (new WindowAdapter ()
                               {
                                   public void windowClosing
                                                       (WindowEvent w)
                                   {
                                      s.setActive (false);
                                      h.stop ();
                                      h.destroy ();
                                      System.exit (0);
                                   }
                               });
   }
}
/* The Stub class provides a mechanism for obtaining information from
   the run-time environment.  Typically, this environment is maintained
   by a Web browser.  For this program, a Web browser environment is
   being simulated. */
class Stub implements AppletStub
{
   private boolean active = false;
   private Hashtable ht = new Hashtable ();
   private Context c;
   // Create a new Stub object.  The application's array of command
   // arguments are passed to this constructor, where they are saved
   // in a Hashtable object, for later retrieval by the getParameter
   // method.
   Stub (String [] args)
   {
      c = new Context (); // Create an applet context.
      // Make sure an even number of arguments has been passed.
      if ((args.length & 1) != 0)
          return;
      for (int i = 0; i < args.length; i += 2)
           ht.put (args [i], args [i + 1]);
   }
   // Return the current state of an applet.  During initialization,
   // the applet is not active (and this method returns false).  The
   // applet's active state is set to true just before the start
   // method is called.
   public boolean isActive ()
   {
      return active;
   }
   // Return the complete URL of the HTML document containing the
   // applet.  This URL includes the name of the document's file.
   public URL getDocumentBase ()
   {
      URL u = null;
      try
      {
          u = new URL ("file:///" + (new File ("").getAbsolutePath ()) +
                       "/x.html"); // Use a fake document.
      }
      catch (MalformedURLException e) {}
      return u;
   }
   // Return the complete URL of the applet's .class file(s).  This
   // method is often used with the getImage and getAudioClip
   // methods to load image/audio files relative to the .class files.
   public URL getCodeBase ()
   {
      URL u = null;
      try
      {
          u = new URL ("file:///" + new File ("").getAbsolutePath () + "/");
      }
      catch (MalformedURLException e) {}
      return u;
   }
   // Return the value of the applet parameter, identified by the
   // name argument.  If not present, null is returned.  The Applet
   // class contains a getParameter method that calls this method.
   public String getParameter (String name)
   {
      return (String) ht.get (name);
   }
   // Return a reference to the applet's context.  The Applet class
   // contains a getAppletContext method that calls this method.
   public AppletContext getAppletContext ()
   {
      return c; // Return current applet context.
   }
   // Resize the applet.  The Applet class contains a pair of resize
   // methods that call this method. Note: Web browsers don't permit
   // applets from being resized.
   public void appletResize (int width, int height)
   {
   }
   // The following method is an extra method that is called to set
   // the value of the private active variable.
   public void setActive (boolean active)
   {
      this.active = active;
   }
}
/* The Context class provides a mechanism to control the environment
   in which the program is running.  Typically, this environment is
   maintained by a Web browser.  For this program, a Web browser
   environment is being simulated. */
class Context implements AppletContext
{
   // Load the file located by the url argument.  The Applet
   // class contains a pair of getAudioClip methods that call
   // this method.
   public AudioClip getAudioClip (URL url)
   {
      return Applet.newAudioClip (url);
   }
   // Prepare to load the image located by the url argument.  The
   // image is loaded when needed (by one of Graphics' drawImage
   // methods).  The Applet class contains a pair of getImage
   // methods that call this method.
   public Image getImage (URL url)
   {
      Toolkit tk = Toolkit.getDefaultToolkit ();
      return tk.getImage (url);
   }
   // Fetch the Applet (identified by name) from the current HTML
   // document.
   public Applet getApplet (String name)
   {
      return null;
   }
   // Return an enumeration to all Applets located on the current HTML
   // page.
   public Enumeration getApplets ()
   {
      return null;
   }
   // Show the HTML document, located by the url argument, in the
   // current Web browser window.
   public void showDocument (URL url)
   {
      System.out.println ("Showing document " + url);
   }
   // Show the HTML document, located by the url argument, in the
   // Web browser window, identified by the frame argument.
   public void showDocument (URL url, String frame)
   {
      try
      {
         showDocument (new URL (url.toString () + frame));
      }
      catch (MalformedURLException e) {}
   }
   // Show a status message, identified by the message argument, in
   // the Web browser's status bar.  The Applet class contains a
   // showStatus method that calls this method.
   public void showStatus (String message)
   {
      System.out.println (message);
   }
   // The following three methods are required by SDK 1.4.  To learn
   // about those methods, please refer to the SDK 1.4 documentation.
   public InputStream getStream (String key)
   {
      return null;
   }
   public Iterator getStreamKeys ()
   {
      return null;
   }
   public void setStream (String key, InputStream stream)
   {
   }
}

As you study the source code, you'll encounter methods for loading images (getImage()), loading audio clips (getAudioClip() and newAudioClip()), showing a Webpage (showDocument()), and showing status information (showStatus()). I'll talk about those methods in a future Java 101 article. For now, you might want to check out the Java 2 SDK documentation to learn more about them.

To compile Hybrid, type javac Hybrid.java. Compiling that source file results in the creation of several class files. However, you only need to focus on the Hybrid.class file. After compiling successfully, we'll first run Hybrid as an application.

The Hybrid program requires an image file and a sound file. Any image and sound file can be specified as command arguments to Hybrid. I've chosen an image of a cartoon character that serves as Sun's Java mascot. I've stored that character, known as Duke (who looks like a drunken penguin), and its image in duke.gif. In addition, I've selected a giggling sound, which I imagine sounds like Duke after a few cocktails. Type either of the following lines below to run Hybrid as an application. Make sure the image and sound files are located in the same directory as Hybrid.class and the other class files.

java Hybrid image duke.gif sound giggle.wav
java Hybrid sound giggle.wav image duke.gif

When run, Hybrid displays a GUI consisting of an image of Duke and a pair of buttons. If you press the Giggle button, Duke will giggle. If you press the Visit Javasoft button, you won't jump to Javasoft's Webpage because showDocument has not been written to do that. Figure 3 illustrates Hybrid's GUI.

Figure 3. Hybrid's GUI

Now run Hybrid as an applet. To do that, you'll need an HTML file containing code similar to that shown in Listing 6.

Listing 6. Hybrid.html

<applet code="Hybrid.class" width=300 height=200>
  <param name="image" value="duke.gif">
  <param name="sound" value="giggle.wav">
</applet>

If you choose to run this applet by using appletviewer, you still will not advance to Javasoft's Webpage. The appletviewer program is not a real browser; it only recognizes <applet> (and a few other tags). However, if you choose to run this applet via a Web browser, you will arrive at that Webpage, from which you can obtain the latest information on Java. (Note: If you run Hybrid in a Web browser, you will probably not hear Duke giggle. That is because many browsers contain older JVMs that do not recognize the WAV file format -- so they will not recognize giggle.wav. You can rectify that problem by using Java Plug-in.)

Review

Java 101 is changing. This article has set the tone for a column that will completely explore Java 2 Standard Edition Version 1.4 over the next few years. The sidebar, A Road Map, details where we'll go and what we'll discover.

In this article, I presented applications, applets, and hybrid programs, and described their architectures and how to run them.

Next month, I start exploring Java's non-object-oriented language basics.

Jeff Friesen has been involved with computers for the past 20 years. He holds a degree in computer science and has worked with many computer languages. Jeff has also taught introductory Java programming at the college level. In addition to writing for JavaWorld, he wrote his own Java book for beginners -- Java 2 By Example, Second Edition (Que Publishing, 2001) -- and helped write a second Java book, Special Edition Using Java 2 Platform (Que Publishing, 2001). Jeff goes by the nickname Java Jeff (or JavaJeff). To see what he's working on, check out his Website at http://www.javajeff.com.

Learn more about this topic

1 2 3 Page 3
Page 3 of 3