.
.
Java Technology Fundamentals Newsletter header
    March 31, 2003    

In this Issue

imageJava Programming Language Basics: Understanding Applets, Part 2
imageJava Bits: Applet Security
imageMaking Sense of the Java Class Libraries: Creating Menus
imageProgram Challenge: Create an applet
imageTake an Online Quiz: Test what you learned
imageNew to Java Technology Programming Center Updates: Introducing Java Technology Workbook
imageFor More Information: Read articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

.

Java Programming Language Basics

Understanding Applets, Part 2

Previously, you learned that developing applets involved subclassing the java.applet.Applet class. This holds for all applets meant to run inside web browsers, no matter what. Sometimes though, when creating your own applets, you don't subclass the Applet class directly. Instead, you subclass a different class, which has subclassed the applet. This allows you to share common code and manage some behavior from a common parent class. Good object-oriented design stuff.

One instance you could implement this is would be when creating an applet that needs to use the Swing component classes. Those applets shouldn't subclass Applet directly but instead should subclass the javax.swing.JApplet class. By subclassing JApplet, the new class works more easily within the Swing framework. However, there are some differences between the two that you should be aware of.

Typically, one adds components to an applet with the add method, as in applet.add(component) or applet.add(component, constraints). With Swing applets, this isn.'t the case. Swing applets contain a single component or content pane. Instead of adding components to the applet itself, you need to add it to the content pane with applet.getContentPane().add(component) or applet.getContentPane().add(component, constraints).

A side effect of this difference is that Swing applets can have menus, whereas regular applets can't (without coding a menu yourself). Some other side effects of this content pane are some layout manager differences. With the standard Applet subclass, the default layout manager for the component is a FlowLayout. That means that as you add components, they are sized to their preferred size, and set out like a typewriter with word wrap, a line at a time, and only if the whole word (component) fits before moving down to the next line.

Because JApplet. as an internal content pane, there is a different layout manager by default, a BorderLayout, allowing you to layout components in the different areas of the screen. In both cases, you can change the layout manager away from the default. The key thing is the default is different in each. There are some other minor differences, but those are the most visible.

To create a simple Swing applet with a handful of components in it, you might do the following:

import java.awt.*;
import javax.swing.*;

public class SwingApplet extends JApplet {

   public void init() {

     Container contentPane = getContentPane();
     contentPane.add(new JButton("North"), BorderLayout.NORTH);
     contentPane.add(new JButton("South"), BorderLayout.SOUTH);
     contentPane.add(new JButton("West"), BorderLayout.WEST);
     contentPane.add(new JButton("East"), BorderLayout.EAST);
     contentPane.add(new JButton("Center"), BorderLayout.CENTER);
   }
}
.
.

Java Bits

Applet Security

Because applets are programs intended to run within a web browser, severe restrictions are placed on what the applet can do, to protect the environment where they execute. Without these restrictions, applets could be a direct vehicle for someone to interfere with your system.

Java programs are run within a controlled environment called a sandbox and managed by a security manager, an object that provides methods that determine what an applet can and cannot do. Along with the security manager, a security policy defines what the applet's limitations are. One part of this the policy file.

A policy file is an ASCII text file and can be composed via a text editor or the graphical Policy Tool utility (policytool). The system policy file is by default located at:

java.home/lib/security/java.policy (Solaris)
java.home\lib\security\java.policy (Win32)

Unless the policy file states otherwise, an applet cannot:

  • Have access to files on the local computer.
  • Invoke other programs on the local computer.
  • Communicate with any computer other than the computer that maintains the HTML page for the applet.

When the applet is launched, it must be launched with the policy file to gain access. Sometimes the permissions in the policy file require an applet be signed to gain access to some URLs and not signed for access to others. All unsigned applets are run under the standard applet security model.

If usePolicy is NOT DEFINED in the java.policy file, then a signed applet has the AllPermission permission if Java Plug-in can verify the signers, and the user agrees to granting the AllPermission permission when prompted.

If usePolicy is DEFINED, then a signed applet has only the permissions defined in java.policy and no prompting occurs.

As of version J2SE 1.4, the Java Plug-In allows you to set applet behavior, including signing applets, and setting options for debugging.

A signed applet is accompanied by a certificate, which identifies the applet signer and prevents others from tampering with the applet. Certificates are issued by Certificate Authorities, such as the U.S. Postal Service or Verisign.

For signing of applets, the jarsigner tool is used:

  • Jarsigner - a tool that is shipped as part of the Java 2 SDK.
    Command is jarsigner.

A digital signature is a string of bits that is computed from some data (the data being "signed") and the private key of an entity, a person or company. Like a handwritten signature, a digital signature has many useful characteristics:

  • Its authenticity can be verified through a computation that uses the public key corresponding to the private key used to generate the signature.

  • It cannot be forged, assuming the private key is kept secret.

  • It is a function of the data signed and thus can't be claimed to be the signature for other data as well.

  • The signed data cannot be changed; if it is, the signature will no longer verify as being authentic.

In order for an entity's signature to be generated for a file, the entity must first have a public/private key pair associated with it, and also one or more certificates authenticating its public key. A certificate is a digitally signed statement from one entity, saying that the public key of some other entity has a particular value.

The jarsigner tool uses key and certificate information from a keystore to generate digital signatures for JAR files. A keystore is a database of private keys and their associated X.509 certificate chains authenticating the corresponding public keys.

The keytool utility is used to create and administer keystores.

The following are basic steps in setting up an applet. Not all steps are necessary. It depends on the applet and what access you want it to have:

  1. Create and Compile the applet

  2. Create a JAR file for the applet classes
    For example:
    jar cvf SignedApplet.jar SignedAppletDemo.class

  3. Generate Keys
    For example:
    keytool -genkey -alias signFiles -keystore susanstore -keypass kpi135 -dname "cn=jones" -storepass ab987c

  4. Sign the JAR file
    For example:
    jarsigner -keystore susanstore -storepass ab987c -keypass kpi135 -signedjar SSignedApplet.jar SignedApplet.jar signFiles
    (Or use Java Plug-In Control Panel)

  5. Export the Public Key Certificate
    For example:
    keytool -export -keystore susanstore -storepass ab987c -alias signFiles -file SusanJones.cer
    (Or use Java Plug-In Control Panel)

  6. Import the Certificate as a Trusted Certificate
    For example:
    keytool -import -alias susan -file SusanJones.cer -keystore raystore -storepass abcdefgh
    (Or use Java Plug-In Control Panel)

  7. Create the policy file policytool or text editor

    Using the Policy Tool saves typing and eliminates the need for you to know the required policy file syntax, thus reducing errors. (See For More Information)

  8. Run the applet
    appletviewer -J-Djava.security.policy=Write.jp
    (Note: the policy file has been saved as Write.jp)
.
.

Making Sense of the Java Class Libraries

Creating Menus

Menus are common in most applications, and allow users to navigate and use different features in an application. Fortunately, menus are easily created for applets.

The Java API provides the following classes to use to create menus:

  • JMenuBar - Groups together JMenu instances.

  • JMenu - Represents a menu title that is contained within the menu bar. It also holds a collection of JMenuItem instances and other submenus.

  • JMenuItem - A menu item, displayed as a word or phrase. Clicking a JMenuItem produces an ActionEvent.

Menu items can also include instances of the following classes:

  • JCheckBoxMenuItem - This class depicts an off or on state with a graphical check mark or other glyph for check boxes.

  • JRadioButtonMenuItem - This class also depicts an off or on state with graphical radio buttons that are placed in a group. Only one option can be selected at a time if the radio buttons are in a group.

Constructing a menu takes only a few steps:

  1. Create a menu bar object by calling the JMenuBar constructor:

    JMenuBar mb = new JMenuBar();

  2. Create a menu object by calling the JMenu constructor and providing a string for the menu name:

    JMenu help = new JMenu("Help");

  3. Call the JMenuBar add method to add the menu to the menu bar:

    mb.add(help);

  4. Create items for the menu by calling the JMenuItem constructor and providing a String for the items titles:

    JMenuItem about = new JMenuItem("About");

  5. Register items with listeners as necessary:

    about.addActionListener(new java.awt.event.ActionListener());

  6. Once your menus are complete, set the menu bar in the applet by calling the setJMenuBar method:

    setJMenuBar(mb);

The following class illustrates the concepts above by creating an applet with three menus. The Help menu has a menu item called About that when selected pops up a JOptionPane window. The Colors menu demonstrates radio buttons used within menus.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingApplet extends JApplet{

 JMenuBar mb;
 JRadioButtonMenuItem rb;
 
   public void init() {
     Container c = getContentPane();
     c.setBackground(Color.WHITE);
     
     //Create a menu bar.
     mb = new JMenuBar();
     
     //Create a menu.
     JMenu file = new JMenu("File");
     
     //Add menu items to the menu.
     file.add(new JMenuItem("Open"));
     //Add a line separator
     file.addSeparator();
     file.add(new JMenuItem("Save"));
     file.add(new JMenuItem("Close"));
     //Add the File menu and items to the
     //menu bar.
     mb.add(file);
     
     //Create another menu called Help.   
     JMenu help = new JMenu("Help");
     //Create a menu item with and register
     //it with a listener.    
     JMenuItem about = new JMenuItem("About");
     help.add(about);
     about.addActionListener(new java.awt.event.ActionListener(){
       public void actionPerformed(ActionEvent e) {
         about_actionPerformed(e);
         }
       }); 
     //Add the Help menu and items to the menu bar
     mb.add(help);
     
     //Create a menu called Colors that will have a 
     //submenu with radio buttons.     
     JMenu subMenu= new JMenu("Colors");
     
     ButtonGroup group = new ButtonGroup();
     subMenu.add(rb = new JRadioButtonMenuItem("Blue", true));
     group.add(rb);
     subMenu.add(rb = new JRadioButtonMenuItem("Red"));
     group.add(rb);
     subMenu.add(rb = new JRadioButtonMenuItem("White"));
     group.add(rb);
     subMenu.add(rb = new JRadioButtonMenuItem("Black"));
     group.add(rb);
     //Add to menu bar.
     mb.add(subMenu);
        
     //Set the menu bar in the applet.
     setJMenuBar(mb);
   }
    //Provides the functionality of the About menu item.
    public void about_actionPerformed(ActionEvent e) {
      JOptionPane.showMessageDialog(this,"Swing Applet, 1.0.");
      }
}

When the applet class is run in appletviewer or your browser, you should see the following:

SwingApplet figure 1

SwingApplet figure 2

Source code

.
.

Program Challenge

Write an applet that loads pages from anywhere on the web and saves HTML content on the local hard drive. The applet needs to be signed and trusted such that network access to anywhere is permissible as is access to the local file system. The applet screen should only show the page within a JTextArea with load and save options available within a menu.

See a possible solution to the Challenge

.
.

Take an Online Quiz

Test what you learned about creating menus and applet security.

.
.

New to Java Technology Programming Center

Introducing Java Technology Workbook! The best way to learn programming is by programming. This online workbook has exercises and the solutions to challenge your Java programming knowledge. Each month a new exercise will be added to this section of the web site.

Java Technology Workbook

.
.

For More Information

Policy Tool

Java Plug-in 1.4 Developer Guide Contents

Signed Applets, Browsers, and File Access

Applet Security FAQ

Lesson: Quick Tour of Controlling Applets

.
.

Downloading the Java 2 Platform

For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the J2SE development kit.

.
.
.

Reader Feedback

  Very worth reading    Worth reading    Not worth reading 

If you have other comments or ideas for future newsletters, please type them here:

 

Have a question about Java programming? Use Java Online Support.

.
.

Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:

- Core Java Technologies Newsletter. Learn about new products, tools, resources, and events of interest to developers working with core Java technologies.
- Wireless Developer Newsletter. Learn about the latest releases, tools, and resources for developers working on wireless and Java Card technologies and applications.
- Core Java Technologies Tech Tips (formerly JDC Tech Tips) Get expert tips, sample code solutions, and techniques for developing in the Java 2 Platform, Standard Edition (J2SE)
You can subscribe to these and other JDC publications on the JDC Newsletters and Publications page

IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html


Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: dana.nourie@sun.com

Go to the subscriptions page to subscribe or unsubscribe to this newsletter.

ARCHIVES: You'll find the Java Technology Fundamentals Newsletter archives at:
http://developer.java.sun.com/developer/onlineTraining/new2java/supplements/


Copyright 2003 Sun Microsystems, Inc. All rights reserved. 4150 Network Circle, Santa Clara, CA 95054

Trademark Information: http://www.sun.com/suntrademarks/
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.


Sun Microsystems, Inc.
image
image