Java Reference
In-Depth Information
Note
You can create signed applets to circumvent the security restrictions. See Supplement
III.S, Signed Applets, for detailed instructions on how to create signed applets.
signed applet
18.5
List some security restrictions on applets.
Check
Point
18.5 Enabling Applets to Run as Applications
You can add a main method in the applet to enable the applet to run as a standalone
application.
Key
Point
Despite some differences, the JFrame class and the JApplet class have a lot in common.
Since they both are subclasses of the Container class, all their user-interface components,
layout managers, and event-handling features are the same. Applications, however, are
invoked from the static main method by the Java interpreter, and applets are run by the Web
browser. The Web browser creates an instance of the applet using the applet's no-arg con-
structor and controls and executes the applet.
In general, an applet can be converted into an application without loss of functionality. An
application can be converted into an applet as long as it does not violate the security restric-
tions imposed on applets. You can implement a main method in an applet to enable the applet
to run as an application. This feature has both theoretical and practical implications. Theoret-
ically, it blurs the difference between applets and applications: You can write a class that is
both an applet and an application. From the standpoint of practicality, it is convenient to be
able to run a program both ways.
How do you write such programs? Suppose you have an applet named MyApplet . To
enable it to run as an application, you only need to add a main method in the applet, as follows:
VideoNote
Run applets standalone
public static void main(String[] args) {
// Create a frame
JFrame
create frame
frame
= new JFrame( "Applet is in the frame" );
// Create an instance of the applet
MyApplet
applet
= new MyApplet();
create applet
// Add the applet to the frame
frame.add(applet, BorderLayout.CENTER);
add applet
// Display the frame
frame.setSize( 300 , 300 );
frame.setLocationRelativeTo( null ); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
show frame
frame.setVisible( true );
}
You can revise the DisplayLabel class in Listing 18.1 to enable it to run as a standalone
application (often abbreviated as “run standalone”) by adding a main method, as shown in
Listing 18.3.
run standalone
L ISTING 18.3 New DisplayLabel.java with a main Method
1 import javax.swing.*;
2
3
4
5 add( new JLabel( "Great!" , JLabel.CENTER));
6 }
7
public class DisplayLabel extends JApplet {
public DisplayLabel() {
 
 
Search WWH ::




Custom Search