Java Reference
In-Depth Information
You can add a main method to enable this applet to run as a standalone application. The
applet takes the parameters from the HTML file when it runs as an applet and takes the para-
meters 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.
L ISTING 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 */
11
12
13 @Override /** Initialize the applet */
14 public void init() {
15 {
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
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
private boolean isStandalone = false ;
isStandalone
if (!isStandalone)
applet params
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
46
47
applet.isStandalone = true ;
standalone
// Get parameters from the command line
48
49
50
applet.getCommandLineParameters(args);
command params
// Add the applet instance to the frame
51
frame.add(applet, BorderLayout.CENTER);
 
Search WWH ::




Custom Search