Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

When to use applets instead of HTML forms: Three easy techniques

Using applets for web page menus and database interactions

  • Print
  • Feedback

Page 3 of 7

 

Using applets for web page menus

HTML has a <MENU> tag but it was deprecated in HTML 4.01 and redefined in HTML 5. It is currently not supported by any of the major browsers (if you use it you get buttons arranged in an un-numbered list). Developers who need to create a web page menu typically do so by using CSS to transform HTML lists into menu bars. A savvy developer who has enough faith in browser implementations of CSS can even develop complex drop-down menus using the CSS hover and float attributes (see Resources) -- but the key word here is faith. A much simpler and more reliable way to create multi-level menus is to build them using Java applets.

Menus in Java applets work the same that they do in Java desktop applications. You can have multiple levels, with the topmost being based on the JMenuBar class. Submenus and sub-submenus are based on the JMenu class, and the lowest-level menus are based on JMenuItems. You can avoid the boring grays associated with Windows desktop applications by setting custom font colors and background colors for your menus. Java also allows you to define both accelerators and mnemonics, but your browser will likely prevent the keystrokes for these to get through. You can process menu events by implementing an ActionListener, either in your main JApplet class or as anonymous inner classes.

In order to use a menu item to change the URL being displayed by the browser you need to call the showDocument method of the AppletContext. This method is passed as a URL object and a string containing a target (_self, _blank, window name, etc.), as shown in Listing 2. If you encode parameters on the URL then it is important to be sure that they contain only valid characters. (More about this in the next section.)

Listing 2. Code to process a menu item selection

/**
 *
 *  Process the CNN menu item
 *
 */
 private void cnnItemActionPerformed(java.awt.event.ActionEvent evt) {

  try{
      URL link = new URL("http://www.cnn.com");
      getAppletContext().showDocument(link,target);
    }

    catch(MalformedURLException ex) {
        showStatus("Bad URL: http://www.cnn.com");
     }
 }

Figure 1 shows a web page with an applet menu. The applet is sitting along the top of the page with a frame below it that holds the body of the page. This particular applet menu allows the user to select from a set of news, sports, and weather websites. The applet accepts as parameters the font family, font size, foreground, and background colors of the menu components.

Figure 1. MenuApplet (click to enlarge)

The HTML code for displaying the above applet is shown in Listing 3. Note the use of the deployJava.js script provided by Oracle. This script handles the preferences of various browsers for Applet, Object, and Embed tags. The URLs themselves are coded within the applet, but it would not be difficult to generalize the MenuApplet class and pass these as parameters as well.

Listing 3. HTML code used to display MenuApplet

<!DOCTYPE html>
<HTML>

 <HEAD>
      <script src="http://www.java.com/js/deployJava.js"></script>
</HEAD>
<BODY>
<script>
  var attributes = {id: "MenuApplet",
              code: "applets.MenuApplet.class",
              archive: "MenuApplet.jar",
              width:"100%", height:"40" };
  var parameters = {target:"window1", fontfamily:"Arial", fontsize:"28",
                    fontcolor:"4169E1", bgcolor:"FFFFFF"};
  var version = '1.6';
  deployJava.runApplet(attributes, parameters, version);
</script>

<IFRAME name="window1" height=700 width=100%></IFRAME>
</BODY>
</HTML>

The applet was built with NetBeans and is contained within the project called MenuApplet, which is part of the source file for this article. The code to build the JMenubar and its submenus was generated by NetBeans and isn't shown below. I could have used NetBeans to set the properties of each menu element, but I chose to make the font family, size, and color choice dynamic by passing the values in from the HTML to the applet via parameters. The init method of the applet retrieves the parameters, parses the font size and colors, creates the font and color objects, then calls a recursive routine to set the font for each JMenuItem and JMenu. I did it this way in order to demonstrate the flexibility of the JApplet’s menu system.

Note that this applet implementation doesn't need to be signed because no extra permissions are required.

Listing 4. init and setMenuFonts methods

public void init() {

        /* Create and display the applet */
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        //
        // get the target of the showDocument calls
        //
        target = this.getParameter("Target");
        if(target == null)
            target="_self";  // assume self if the parameter is missing
        //
        // access the font information from the parameters
        //
        String fontsize = this.getParameter("fontsize");
        String fontfamily = this.getParameter("fontfamily");
        String fontcolor = this.getParameter("fontcolor");
        String bgcolor = this.getParameter("bgcolor");
        //
        // create the font and the colors if all parameters are present
        //
        if(fontsize != null && fontfamily != null && fontcolor != null)
        {
         Font menuFont;
         Color fcolor = Color.BLACK;
         Color bcolor = Color.WHITE;
          try{
            int size = Integer.parseInt(fontsize);
            int colorf = Integer.parseInt(fontcolor,16);
            int colorb = Integer.parseInt(bgcolor,16);
            menuFont = new Font(fontfamily, Font.PLAIN, size);
            fcolor = new Color(colorf);
            bcolor = new Color(colorb);

            synchronized(menuBar.getTreeLock())  // protect the UI
            {
             menuBar.setBackground(bcolor); // set the menu bar background
             Component[] comps = menuBar.getComponents(); // get all the components
             for(int i = 0; i < comps.length; i++)
             {
              setMenuFonts(comps[i],menuFont, fcolor,bcolor);  // recursively set fonts
             }
            }
          }
          catch(NumberFormatException nfex)
          {
            // any parsing errors will cause the default fonts to be used.
          }
        }
    }
/**
 * Recursively set all the fonts and colors for the JMenu or JMenuItem component passed
 *
 * @param c - Component (JMenu or JMenuItem)
 * @param f - font
 * @param fcolor - foreground color
 * @param bcolor - background color
 */
    private void setMenuFonts(Component c, Font f, Color fcolor, Color bcolor)
    {
     //
     // set the properties
     c.setForeground(fcolor);
     c.setBackground(bcolor);
     c.setFont(f);
     //
     // recurse only if it is a JMenu
     //
     if(c instanceof JMenu)
     {
       ((JMenu)c).setOpaque(true);  // force the JMenus to be opaque
       Component[] comps = ((JMenu)c).getMenuComponents();
       for(int i = 0; i < comps.length; i++)
       {
        setMenuFonts(comps[i],f,fcolor,bcolor); // recurse for each sub item
       }
     }
    }

  • Print
  • Feedback

Resources