Java Reference
In-Depth Information
52
53
// Invoke applet's init method
54
55
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
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(
1
);
71 }
72
else
{
73 x = Integer.parseInt(args[
0
]);
74 y = Integer.parseInt(args[
1
]);
75 message = args[
2
];
76 }
77 }
78 }
applet.init();
applet.start();
frame.setVisible(
true
);
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. Sample runs of the program as an application and as
an applet are shown in Figure 18.7.
(a)
F
IGURE
18.7
The
DisplayMessageApp
class can run as an applet in (a) and as an
application in (b).
(b)
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 appli-
cation runs just like an applet.
The
main
method sets
isStandalone
as
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.
omitting
main
method
✓
✓
Check
18.12
Point
How do you pass parameters to an applet?
18.13
Where is the
getParameter
method defined?