Java Reference
In-Depth Information
<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);
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.6.
L ISTING 18.5 DisplayMessage.java
1 import javax.swing.*;
2
3 public class
DisplayMessage extends JApplet
{
4 @Override /** Initialize the applet */
5 {
6 // Get parameter values from the HTML file
7 String message =
public void init()
getParameter( "MESSAGE" )
;
getParameter
getParameter( "X" )
8
int x = Integer.parseInt(
);
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
17 add(messagePanel);
18 }
19 }
add to applet
F IGURE 18.6
The applet displays the message Welcome to Java passed from the HTML
page.
The program gets the parameter values from the HTML file in the init method. The val-
ues are strings obtained using the getParameter method (lines 7-9). Because x and y are
int s, 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.
 
 
Search WWH ::




Custom Search