Java Reference
In-Depth Information
public static void main(String[] args) {
8
9 // Create a frame
10 JFrame frame = new JFrame( "Applet is in the frame" );
11
12 // Create an instance of the applet
13 DisplayLabel applet = new DisplayLabel();
14
15 // Add the applet to the frame
16 frame.add(applet);
17
18 // Display the frame
19 frame.setSize( 300 , 100 );
20 frame.setLocationRelativeTo( null ); // Center the frame
21 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
22 frame.setVisible( true );
23 }
24 }
new main method
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.
Note that you can add an applet to a container, but not a frame to a container. A frame is a
top-level container that cannot be embedded in another container.
18.6
How do you add components to a JApplet ? What is the default layout manager of
JApplet ?
Check
Point
18.7
Can you place a frame in an applet?
18.8
Can you place an applet in a frame?
18.9
What are the differences between applications and applets? How do you run an
application, and how do you run an applet? Is the compilation process different for
applications and applets?
18.6 Applet Life-Cycle Methods
The Web browser controls and executes applets using the applet life-cycle methods.
Key
Point
Applets are actually run from the applet container , which is a plug-in of a Web browser. A
plug-in is a software component that can be added into a larger software to provide additional
functions. 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 execution 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 per-
form desired operations. Figure 18.5 shows how the applet container calls these methods.
applet container
Applet container
creates the applet
Applet container
invokes init()
Applet container
invokes start()
Applet container
invokes stop()
Loaded
Created
Initialized
Started
Stopped
Applet container
invokes destroyed()
Applet container
invokes start()
Applet container
loads the applet
Destroyed
F IGURE 18.5
The applet container uses the init , start , stop , and destroy methods to control the applet.
 
 
 
Search WWH ::




Custom Search