To convert a GUI application to an applet you'll need to follow a few
steps.
-
To make things easier, test your program as an application. The easiest
way to convert the application is to create your GUI class that extends
JFrame so that it launches the whole program via a parameterless
constructor. For example, suppose you have a class JoggleGui
that extends JFrame. Create a class (it could be JoggleGui,
or a separate class) so that the program is started and run with a
very simple main:
public static void main(String args[])
{
JoggleGui jg = new JoggleGui();
}
This shouldn't be too hard, the constructor can call other functions in
other classes, but this will make conversion to an applet simplest.
- Copy the class that extends JFrame (assume it's JoggleGui
for this discussion) to another file called JoggleApplet,
change the name of the class, and make it extend JApplet instead of
JFrame. Change the constructor of the new class so that instead of
having the same name as the class, e.g., JoggleApplet it's a
void function named init. This means you won't have a
constructor, just a function named init.
- Remove calls to setSize, setTitle, pack,
and any window listener calls, e.g.,
setDefaultCloseOperation. Compile the program---if something
doesn't compile just comment it out for now.
- Create a simple web page with the following body.
- Put all the class files your program needs in a jar file, the name
of the jar file is used in the ARCHIVE line of the web page, so in this
example we use joggle.jar. To create a jar file use commands
similar to tar/gtar. To create a jar file use the cf option as follows:
jar cf joggle.jar *.class
Don't forget to recreate the jar file every time you recompile any
class that's used in the applet. Your application loads .class files
from the file system, but the applet will load the .class files from the
jar file.
For information on reading files and images from jar files
this resource page
- Use appletviewer to test the applet. WHen it's working you can use
the Java Plug-in and converter to run the 1.2/Swing applet in a
browser. If you have JDK1.3 (or 1.2) on your windows machine,
you most likely already have the plug-in. To get the converter
visit
http://www.java.sun.com/products/plugin/ and download the
converter. The converter transforms your html file into one that both
Netscape and IE will understand.
Note: on the acpub system which uses jdk1.4 or jdk1.3, there's
a program called HtmlConvert (get the case right). You can
run this using the format below to convert foo.html.
HtmlConvert foo.html
- You can pass size and other parameters to your applet, see the
Java tutorial or another book for details.