Running applets from the command line
There are times when youd like to make a windowed program do something else other than sit on a Web page. Perhaps youd also like it to do some of the things a regular application can do, but still have the vaunted instant portability provided by Java. In previous chapters in this book weve made command-line applications, but in some operating environments (the Macintosh, for example) there isnt a command line. So for any number of reasons, youd like to build a windowed, non-applet program using Java. This is certainly a reasonable desire.
The Swing library allows you to make an application that preserves the look and feel of the underlying operating environment. If you want to build windowed applications, it makes sense to do so[78] only if you can use the latest version of Java and associated tools so you can deliver applications that wont confound your users. If for some reason youre forced to use an older version of Java, think hard before committing to building a significant windowed application.
Often youll want to be able to create a class that can be invoked as either a window or an applet. This is especially convenient when youre testing the applets, since its typically much faster and easier to run the resulting applet-application from the command line than it is to start up a Web browser or the Appletviewer.
To create an applet that can be run from the console command line, you simply add a main( ) to your applet that builds an instance of the applet inside a Jframe.[79] As a simple example, lets look at Applet1b.java modified to work as both an application and an applet:
//: c14:Applet1c.java
// An application and an applet.
// <applet code=Applet1c width=100 height=50></applet>
import javax.swing.*;
import java.awt.*;
public class Applet1c extends JApplet {
public void init() {
getContentPane().add(new JLabel("Applet!"));
}
// A main() for the application:
public static void main(String[] args) {
JApplet applet = new Applet1c();
JFrame frame = new JFrame("Applet1c");
// To close the application:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(100,50);
applet.init();
applet.start();
frame.setVisible(true);
}
} ///:~
main( ) is the only element added to the applet, and the rest of the applet is untouched. The applet is created and added to a JFrame so that it can be displayed.
You can see that in main( ), the applet is explicitly initialized and started because in this case the browser isnt available to do it for you. Of course, this doesnt provide the full behavior of the browser, which also calls stop( ) and destroy( ), but for most situations its acceptable. If its a problem, you can force the calls yourself.[80]
Notice the last line:
frame.setVisible(true);
Without this, you wont see anything on the screen.