Creating Applets

An applet is not a small piece of fruit. Rather, it's a Java application that's designed to run in a browser window on an Internet user's computer. When an Internet user visits a Web page that contains an applet, the Java applet class is downloaded to the user's computer and run there. The applet takes over a portion of the page and, within that space, can do anything it wants.

Applets are, at least in most cases, Swing applications. As a result, everything that's covered in Book VI applies to applets. In this chapter, you create applets that include Swing components. Then you add an applet to a Web page so anyone who views the page can use it.

Understanding Applets

An applet is similar to a Swing application, with several crucial differences:

Other than these differences and restrictions, an applet works pretty much the same as a Swing application. In fact, the Swing components inside the applet look and behave exactly like they do in a stand-alone Swing application. Thus, applets let you create Swing applications and run them on any computer, anywhere in the world. Right?

Would that it were so. Unfortunately, the company that makes the world's most popular Web browser, whose name I won't mention but whose initials are MICROSOFT, hasn't always played nice with Sun. Or maybe Sun hasn't always played nice with Microsoft. Who knows. Either way, the result has been a mess when it comes to whether or not users' computers can run applets, and if they can, what version of Java they support. Users can download the Java plug-in from Sun, but many users either don't want to take the time, don't understand the process, or don't trust it. (The main Java plug-in download site is http://www.java.com.)

As a result, applets aren't the best way to create Web-based applications that you expect to be used by the masses. The biggest sites on the Internet, such as eBay and Amazon, are not implemented with applets; instead, they're built using tools such as servlets and Java Server Pages as described in the other chapters of Book VII.

The JApplet Class

As I've already mentioned, an applet extends the JApplet class rather than the JFrame class. For the most part, the JApplet class works pretty much the same as the JFrame class. As a result, you can add panels and other components to it, create menus, doodle on it, and so on. Table 1-1 lists the most commonly used methods of the JApplet class.

Table 1-1: Useful JApplet Constructors and Methods

Open table as spreadsheet

Constructor

Description

JApplet()

Creates a new applet. You don't usually need to call the JApplet constructor because it's called automatically when the browser loads the applet.

Open table as spreadsheet

Method

Description

void add(Component c)

Adds the specified component to the applet.

void destroy()

Called by the browser to inform the applet that its memory is about to be reclaimed by the JVM. Most applets don't need to override this method.

void init()

Called by the browser to inform the applet that it has been loaded. This method takes the place of the JFrame constructor for a Swing application.

void setLayout (LayoutManager layout)

Sets the layout manager used to control how components are arranged when the applet is displayed. The default is the Border Layout manager.

void setLocation (int x, int y)

Sets the x and y position of the applet on-screen. The top-left corner of the screen is 0, 0.

void setLocationRelativeTo (Component c)

Centers the applet on-screen if the parameter is null.

void setSize(int width, int height)

Sets the size of the applet to the specified width and height.

void setJMenuBar (JMenuBar menu)

Sets the menu for this applet.

void start()

Called by the browser to inform the applet to start its execution.

void stop()

Called by the browser when the applet temporarily leaves view. Override this method if you need to stop activities while the applet is hidden.

Looking at a Sample Applet

To see how a complete applet works, Listing 1-1 shows the complete code for an applet that lets the user order a pizza in one of three sizes (Small, Medium, and Large) with one of three toppings (Pepperoni, Mushrooms, and Anchovies). Figure 1-1 shows this applet in action on a Web page.

Figure 1-1: The pizza applet in action.

Listing 1-1: The Pizza Order Applet

import javax.swing.*; import java.awt.event.*; import javax.swing.border.*; public class PizzaApplet extends JApplet → 5 { private JButton buttonOK; private JRadioButton small, medium, large; private JCheckBox pepperoni, mushrooms, anchovies; public void init() → 12 { this.setSize(320,200); → 14 ButtonListener bl = new ButtonListener(); JPanel mainPanel = new JPanel(); JPanel sizePanel = new JPanel(); Border b1 = BorderFactory. createTitledBorder("Size"); sizePanel.setBorder(b1); ButtonGroup sizeGroup = new ButtonGroup(); small = new JRadioButton("Small"); small.setSelected(true); sizePanel.add(small); sizeGroup.add(small); medium = new JRadioButton("Medium"); sizePanel.add(medium); sizeGroup.add(medium); large = new JRadioButton("Large"); sizePanel.add(large); sizeGroup.add(large); mainPanel.add(sizePanel); JPanel topPanel = new JPanel(); Border b2 = BorderFactory. createTitledBorder("Toppings"); topPanel.setBorder(b2); pepperoni = new JCheckBox("Pepperoni"); topPanel.add(pepperoni); mushrooms = new JCheckBox("Mushrooms"); topPanel.add(mushrooms); anchovies = new JCheckBox("Anchovies"); topPanel.add(anchovies); mainPanel.add(topPanel); buttonOK = new JButton("OK"); buttonOK.addActionListener(bl); mainPanel.add(buttonOK); this.add(mainPanel); this.setVisible(true); } private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == buttonOK) { String tops = ""; if (pepperoni.isSelected()) tops += "Pepperoni "; if (mushrooms.isSelected()) tops += "Mushrooms "; if (anchovies.isSelected()) tops += "Anchovies "; String msg = "You ordered a "; if (small.isSelected()) msg += "small pizza with "; if (medium.isSelected()) msg += "medium pizza with "; if (large.isSelected()) msg += "large pizza with "; if (tops.equals("")) msg += "no toppings."; else msg += "the following toppings: " + tops; JOptionPane.showMessageDialog(buttonOK, msg, "Your Order", JOptionPane.INFORMATION_MESSAGE); pepperoni.setSelected(false); mushrooms.setSelected(false); anchovies.setSelected(false); small.setSelected(true); } } } }

This is an applet version of a Swing program that is in Book VI, Chapter 3. For the details on how the Swing components work, you can refer to that chapter. Here I just want to point out a few details that are specific to applets:

5

The class extends JApplet instead of JFrame.

12

The init method is overridden, and the code that ordinarily is in the constructor for the JFrame class is placed in the init method.

14

The setSize method is called to set the size of the applet.

Several methods that appeared in the Swing version of this program, however, are removed. In particular, the setTitle and setDefaultCloseAction methods are deleted, because those methods don't apply to applets. From the rest of this method, however, you can see that most of this code is exactly the same as it is for a stand-alone Swing application.

Open table as spreadsheet

Creating an HTML Page for an Applet

To run an applet, you must create an HTML page that includes an APPLET tag that specifies the name of the applet and the size of the region you want to let the applet run inside. The APPLET tag also includes text that's displayed if the Web browser isn't capable of running the applet.

The basic form of the APPLET tag is this:

width height=height> Text to display if applet can't be loaded

For example, here's the HTML file that I used to display the page shown in Figure 1-1:

 

The Pizza Applet

Welcome to the Pizza Applet!

Sorry, your browser isn't able to run Java applets.

Testing an Applet

Java comes with a special program called the applet viewer that lets you quickly run an applet after you compile it. Figure 1-2 shows the pizza applet displayed in the applet viewer.

Figure 1-2: The pizza applet displayed in the applet viewer.

If you're using TextPad, you can invoke the viewer by pressing Ctrl+3 after you compile the applet. From a command prompt, you must first create an HTML file as described in the previous section. Then navigate to the directory that contains the HTML file and type this command:

appletviewer filename

For example, to display the pizza applet with an HTML file named PizzaApplet.html, use this command:

appletviewer PizzaApplet.html

Категории