To make an applet into an application, add a main()method to the applet's class -- you don't have to create a new class. It may seem a little strange that adding a main method to a class will make it into an application, but that's the most common way of doing it. An application is any program that has a main() method. This new main() does what a browser does.
The main method should do the following:
- Create a window (JFrame) to hold the applet.
- Make the window's close box stop the applet.
- Create a new applet object, and add it to the window.
- Start the applet by calling init(), then start().
- Finalize the layout.
- Make the window (with the applet in it) visible.
Example
Here is a very small applet, which just displays some text.
import javax.swing.*;
public class SampleApplet extends JApplet {
public SampleApplet() {
add(new JLabel("This is an Applet."));
}
}
Add a main() method, and it can be used as either an application or an applet.
1 | // File : deployment/appletapp/SampleApplet.java |
- You can use this as an applet and the browser will ignore
main(). - Although
SampleAppletis the name of the class, we need to create an instance of it. An applet is a kind of panel, so it can be used for the contentPane in a JFrame. - Usually only applets which do animation have a
start()method. If your applet doesn't have astart()method, you don't need this call, although it won't cause problems because JApplet has defined a version that does nothing. Similarly withinit()which is commonly used in applets, altho a constructor would be a better choice. If there is noinit(), there's no need to call it.
Some applets may use features that require additional work.
- An applet can call getCodeBase() to find out where it was loaded from to get additional classes, images, or other data, then use the return value to get more things. If an applet does this, then you must define getCodeBase().
- If an applet gets parameters from the web page, you will have to provide a getParameter() method.
- The showStatus() method must be supplied if used by the applet.
No comments:
Post a Comment