17.14. Programming Exercises

 
[Page 546 ( continued )]

16.6. Passing Strings to Applets

In §8.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 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. The syntax for the <param> tag is given below:

 <   param name   = parametername   value   = stringvalue /> 

This tag specifies a parameter and its corresponding string value.

Note

There is no comma separating 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 16.1.

Table 16.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 16.4.


[Page 547]
Listing 16.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); 

This returns the value of the specified parameter.

The applet is given in Listing 16.5. A sample run of the applet is shown in Figure 16.8.

Figure 16.8. The applet displays the message Welcome to Java passed from the HTML page.


Listing 16.5. DisplayMessage.java
(This item is displayed on pages 547 - 548 in the print version)
 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  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 

[Page 548]
 16  // Add the message panel to the 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 16.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.

Listing 16.6. DisplayMessageApp.java
(This item is displayed on pages 548 - 549 in the print version)
 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 if it is application */  11    private boolean   isStandalone =   false   ;  12 13  /** Initialize the applet */  14   public void   init() { 15    if   (!isStandalone)  { 16  // Get parameter values from the HTML file  17 message = getParameter(   "MESSAGE"   ); 18 x = Integer.parseInt(getParameter(   "X"   )); 19 y = Integer.parseInt(getParameter(   "Y"   )); 20 } 21 22  // Create a message panel  23 MessagePanel messagePanel =   new   MessagePanel(message); 24 messagePanel.setFont(   new   Font(   "SansSerif"   , Font.BOLD,   20   )); 25 messagePanel.setXCoordinate(x); 26 messagePanel.setYCoordinate(y); 27 28  // Add the message panel to the applet  29 add(messagePanel); 30 } 31 32  /** Main method to display a message  33  @param args [0] x coordinate  

[Page 549]
 34  @param args [1] y coordinate  35  @param args [2] message  36  */  37   public static void   main(String[] args) { 38  // Create a frame  39 JFrame  frame  =   new   JFrame(   "DisplayMessageApp"   ); 40 41  // Create an instance of the applet  42 DisplayMessageApp  applet  =   new   DisplayMessageApp(); 43 44  // It runs as an application  45  applet.isStandalone =   true   ;  46 47  // Get parameters from the command line  48  applet.getCommandLineParameters(args);  49 50  // Add the applet instance to the frame  51  frame.add(applet, BorderLayout.CENTER);  52 53  // Invoke applet's init method  54  applet.init();  55  applet.start();  56 57  // Display the frame  58 frame.setSize(   300   ,   300   ); 59 frame.setLocationRelativeTo(   null   );  // Center the frame  60 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 61  frame.setVisible(   true   );  62 } 63 64  /** Get command line parameters */  65   private void   getCommandLineParameters(String[] args) { 66  // Check usage and get x, y and message  67   if   (args.length !=   3   ) { 68 System.out.println( 69   "Usage: java DisplayMessageApp x y message"   ); 70 System.exit(     ); 71 } 72   else   { 73 x = Integer.parseInt(args[     ]); 74 y = Integer.parseInt(args[   1   ]); 75 message = args[   2   ]; 76 } 77 } 78 } 

When you run the program as an applet, the main method is ignored. When you run it as an application, the main method is invoked. A sample run of the program as an application and as an applet is shown in Figure 16.9.

Figure 16.9. The DisplayMessageApp class can run as an application and as an applet.


[Page 550]

The main method creates a JFrame object frame and creates a JApplet object applet , then places the applet applet into the frame frame and invokes its init method. The application runs just like an applet.

The main method sets isStandalone true (line 45) so that it does not attempt to retrieve HTML parameters when the init method is invoked.

The setVisible(true) method (line 61) is invoked after the components are added to the applet, and the applet is added to the frame to ensure that the components will be visible. Otherwise, the components are not shown when the frame starts.

Important Pedagogical Note

From now on, all the GUI examples will be created as applets with a main method. Thus you will be able to run the program either as an applet or as an application. For brevity, the main method is not listed in the text.


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net