Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Intro_Java_brief_Liang2011.pdf
Скачиваний:
195
Добавлен:
26.03.2016
Размер:
10.44 Mб
Скачать

618 Chapter 18 Applets and Multimedia

(a)

(b)

FIGURE 18.5 The appletviewer command runs a Java applet in the applet viewer utility.

signed applet

Video Note

Run applets standalone

18.4 Applet Security Restrictions

Java uses the so-called “sandbox security model” for executing applets to prevent destructive programs from damaging the system on which the browser is running. Applets are not allowed to use resources outside the “sandbox.” Specifically, the sandbox restricts the following activities:

Applets are not allowed to read from, or write to, the file system of the computer. Otherwise, they could damage the files and spread viruses.

Applets are not allowed to run programs on the browser’s computer. Otherwise, they might call destructive local programs and damage the local system on the user’s computer.

Applets are not allowed to establish connections between the user’s computer and any other computer, except for the server where the applets are stored. This restriction prevents the applet from connecting the user’s computer to another computer without the user’s knowledge.

Note

You can create signed applets to circumvent the security restrictions. See java.sun.com/ developer/onlineTraining/Programming/JDCBook/signed.html for detailed instructions on how to create signed applets.

18.5 Enabling Applets to Run as Applications

Despite some differences, the JFrame class and the JApplet class have a lot in common. Since they both are subclasses of the Container class, all their user-interface components, layout managers, and event-handling features are the same. Applications, however, are invoked from the static main method by the Java interpreter, and applets are run by the Web browser. The Web browser creates an instance of the applet using the applet’s no-arg constructor and controls and executes the applet.

In general, an applet can be converted to an application without loss of functionality. An application can be converted to an applet as long as it does not violate the security restrictions imposed on applets. You can implement a main method in an applet to enable the applet to run as an application. This feature has both theoretical and practical implications. Theoretically, it blurs the difference between applets and applications. You can write a class that is both an applet and an application. From the standpoint of practicality, it is convenient to be able to run a program in two ways.

18.5 Enabling Applets to Run as Applications 619

How do you write such program? Suppose you have an applet named MyApplet. To enable it to run as an application, you need only add a main method in the applet with the implementation, as follows:

public static void main(String[] args) { // Create a frame

JFrame frame = new JFrame("Applet is in the frame");

// Create an instance of the applet MyApplet applet = new MyApplet();

// Add the applet to the frame frame.add(applet, BorderLayout.CENTER);

// Display the frame frame.setSize(300, 300);

frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);

}

create frame

create applet

add applet

show frame

You can revise the DisplayLabel class in Listing 18.1 to enable it to run standalone by adding a main method in Listing 18.3.

LISTING 18.3 New DisplayLabel.java with a main Method

1 import javax.swing.*;

2

3 public class DisplayLabel extends JApplet {

4public DisplayLabel() {

5add(new JLabel("Great!", JLabel.CENTER));

6

}

 

7

 

 

8

public static void main(String[] args) {

new main method

9// Create a frame

10 JFrame frame = new JFrame("Applet is in the frame"); 11

12// Create an instance of the applet

13DisplayLabel applet = new DisplayLabel();

15// Add the applet to the frame

16

frame.add(applet);

17

 

18// Display the frame

19frame.setSize(300, 100);

20frame.setLocationRelativeTo(null); // Center the frame

21frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

22frame.setVisible(true);

23}

24}

When the applet is run from a Web browser, the browser creates an instance of the applet and displays it. When the applet is run standalone, the main method is invoked to create a frame (line 10) to hold the applet. The applet is created (line 13) and added to the frame (line 16). The frame is displayed in line 22.

620 Chapter 18 Applets and Multimedia

 

18.6 Applet Life-Cycle Methods

applet container

Applets are actually run from the applet container, which is a plug-in of a Web browser. The

 

Applet class contains the init(), start(), stop(), and destroy() methods, known as

 

the life-cycle methods. These methods are called by the applet container to control the execu-

 

tion of an applet. They are implemented with an empty body in the Applet class. So, they do

 

nothing by default. You may override them in a subclass of Applet to perform desired oper-

 

ations. Figure 18.6 shows how the applet container calls these methods.

 

Applet container

Applet container

Applet container

 

Applet container

 

 

 

creates the applet

invokes init()

 

invokes start()

 

invokes stop()

 

 

Loaded

 

 

Created

 

 

Initialized

 

 

Started

 

 

 

 

Stopped

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Applet container

 

Applet container

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

invokes start()

 

invokes destroyed()

 

 

 

 

 

 

 

 

 

 

 

 

 

Applet container

Destroyed

loads the applet

 

FIGURE 18.6 The applet container uses the init, start, stop, and destroy methods to control the applet.

 

18.6.1

The init Method

init()

The init method is invoked after the applet is created. If a subclass of Applet has an initia-

 

lization to perform, it should override this method. The functions usually implemented in this

 

method include getting string parameter values from the <applet> tag in the HTML page.

 

18.6.2

The start Method

start()

The start method is invoked after the init method. It is also called when the user returns to

 

the Web page containing the applet after surfing other pages.

 

A subclass of Applet overrides this method if it has any operation that needs to be per-

 

formed whenever the Web page containing the applet is visited. An applet with animation, for

 

example, might start the timer to resume animation.

 

18.6.3

The stop Method

stop()

The stop method is the opposite of the start method. The start method is called when the

 

user moves back to the page that contains the applet. The stop method is invoked when the

 

user leaves the page.

 

A subclass of Applet overrides this method if it has any operation to be performed each

 

time the Web page containing the applet is no longer visible. An applet with animation, for

 

example, might stop the timer to pause animation.

 

18.6.4

The destroy Method

destroy()

The destroy method is invoked when the browser exits normally to inform the applet that it

 

is no longer needed and should release any resources it has allocated. The stop method is

 

always called before the destroy method.

 

A subclass of Applet overrides this method if it has any operation to be performed before

 

it is destroyed. Usually, you won’t need to override this method unless you wish to release

 

specific resources that the applet created.

 

18.7

Passing Strings to Applets

In §9.5, “Command-Line Arguments,” you learned how to pass strings to Java applications from a command line. Strings are passed to the main method as an array of strings. When the

18.7 Passing Strings to Applets 621

application starts, the main method can use these strings. There is no main method in an applet, however, and applets are not run from the command line by the Java interpreter.

How, then, can applets accept arguments? In this section, you will learn how to pass strings to Java applets. To be passed to an applet, a parameter must be declared in the HTML file and must be read by the applet when it is initialized. Parameters are declared using the <param> tag. The <param> tag must be embedded in the <applet> tag and has no end tag. Its syntax is given below:

<param name = parametername value = stringvalue />

This tag specifies a parameter and its corresponding string value.

Note

No comma separates the parameter name from the parameter value in the HTML code. The

HTML parameter names are not case sensitive.

Suppose you want to write an applet to display a message. The message is passed as a parameter. In addition, you want the message to be displayed at a specific location with x- coordinate and y-coordinate, which are passed as two parameters. The parameters and their values are listed in Table 18.1.

TABLE 18.1 Parameter Names and Values for the

DisplayMessage Applet

Parameter Name

Parameter Value

MESSAGE

"Welcome to Java"

X

20

Y

30

The HTML source file is given in Listing 18.4.

LISTING 18.4 DisplayMessage.html

<html>

<head>

<title>Passing Strings to Java Applets</title> </head>

<body>

<p>This applet gets a message from the HTML page and displays it.</p>

<applet

code = "DisplayMessage.class" width = 200

height = 50

alt = "You must have a Java 2-enabled browser to view the applet"

>

<param name = MESSAGE value = "Welcome to Java" /> <param name = X value = 20 />

<param name = Y value = 30 /> </applet>

</body>

</html>

To read the parameter from the applet, use the following method defined in the Applet class:

public String getParameter(String parametername);

622 Chapter 18 Applets and Multimedia

This returns the value of the specified parameter.

The applet is given in Listing 18.5. A sample run of the applet is shown in Figure 18.7.

FIGURE 18.7 The applet displays the message Welcome to Java passed from the

HTML page.

LISTING 18.5 DisplayMessage.java

 

1

import javax.swing.*;

 

2

 

 

 

 

 

 

 

 

 

3

public class

DisplayMessage extends JApplet

{

 

4

 

/** Initialize the applet */

 

5

 

public void init()

{

 

 

6

 

// Get parameter values from the HTML file

getParameter

7

 

String message =

getParameter("MESSAGE")

;

 

8

 

int x = Integer.parseInt(getParameter("X")

);

 

9

 

int y = Integer.parseInt(getParameter("Y")

);

 

10

 

 

 

 

 

 

 

 

 

11

 

// Create a message panel

 

12

 

MessagePanel messagePanel = new MessagePanel(message);

 

13

 

messagePanel.setXCoordinate(x);

 

14

 

messagePanel.setYCoordinate(y);

 

15

 

 

 

 

 

 

 

 

 

16

 

// Add the message panel to the applet

add to applet

17

 

add(messagePanel);

 

18

}

 

 

 

 

 

 

 

19

}

 

 

 

 

 

 

 

The program gets the parameter values from the HTML in the init method. The values are strings obtained using the getParameter method (lines 7–9). Because x and y are int, the program uses Integer.parseInt(string) to parse a digital string into an int value.

If you change Welcome to Java in the HTML file to Welcome to HTML, and reload the HTML file in the Web browser, you should see Welcome to HTML displayed. Similarly, the x and y values can be changed to display the message in a desired location.

Caution

The Applet’s getParameter method can be invoked only after an instance of the applet is created. Therefore, this method cannot be invoked in the constructor of the applet class. You should invoke it from the init method.

You can add a main method to enable this applet to run standalone. The applet takes the parameters from the HTML file when it runs as an applet and takes the parameters from the command line when it runs standalone. The program, as shown in Listing 18.6, is identical to DisplayMessage except for the addition of a new main method and of a variable named isStandalone to indicate whether it is running as an applet or as an application.

18.7 Passing Strings to Applets 623

LISTING 18.6 DisplayMessageApp.java

1 import javax.swing.*;

2 import java.awt.Font;

3 import java.awt.BorderLayout;

4

5 public class DisplayMessageApp extends JApplet {

6 private String message = "A default message"; // Message to display 7 private int x = 20; // Default x-coordinate

8 private int y = 20; // Default y-coordinate 9

10/** Determine whether it is an application */

11private boolean isStandalone = false;

12

13/** Initialize the applet */

14public void init() {

15if (!isStandalone) {

16// Get parameter values from the HTML file

17message = getParameter("MESSAGE");

18x = Integer.parseInt(getParameter("X"));

19y = Integer.parseInt(getParameter("Y"));

20}

21

22// Create a message panel

23MessagePanel messagePanel = new MessagePanel(message);

24messagePanel.setFont(new Font("SansSerif", Font.BOLD, 20));

25messagePanel.setXCoordinate(x);

26messagePanel.setYCoordinate(y);

27

28// Add the message panel to the applet

29add(messagePanel);

30}

31

32/** Main method to display a message

33@param args[0] x-coordinate

34@param args[1] y-coordinate

35@param args[2] message

36*/

37public static void main(String[] args) {

38// Create a frame

39JFrame frame = new JFrame("DisplayMessageApp");

41// Create an instance of the applet

42DisplayMessageApp applet = new DisplayMessageApp();

44// It runs as an application

45applet.isStandalone = true;

46

47// Get parameters from the command line

48applet.getCommandLineParameters(args);

49

50// Add the applet instance to the frame

51frame.add(applet, BorderLayout.CENTER);

52

53// Invoke applet's init method

54applet.init();

55applet.start();

56

57// Display the frame

58frame.setSize(300, 300);

isStandalone

applet params

standalone

command params

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]