These notes were originally written using applets almost entirely. However, all applet examples are being changed to applications.
appletviewer
program
thereby negating the supposed applet advantages.
init
instead of a contructors,
the fixed size as opposed to using pack
,
lack of I/O capability (without permissions), ...
It's even worse when using Java 1.1 because the lack of a
content pane distorts the program.
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:
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.
import java.awt.*; import javax.swing.*; public class SampleApplet extends JApplet { public static void main(String[] args) { JFrame myWindow = new JFrame("SampleApplet Application"); myWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SampleApplet theApplet = new SampleApplet(); // Create a new object. myWindow.setContentPane(theApplet); // Add to the window. //theApplet.init(); // Needed if defined in applet //theApplet.start(); // Needed if defined in applet myWindow.pack(); // Arrange the components. myWindow.setVisible(true); // Make the window visible. } // Constructor public SampleApplet() { add(new JLabel("This is an Applet and and Application!")); } }
main()
.SampleApplet
is 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.start()
method.
If your applet doesn't have a start()
method, you don't need
this call, although it won't cause problems because JApplet has defined a version
that does nothing.
Similarly with init()
which is commonly used in applets, altho
a constructor would be a better choice. If there is no init()
,
there's no need to call it.Some applets may use features that require additional work.
You need to specify the following values in an applet tag.
width="nn" height="mm"
, where nn and mm
are the width and the height of the area the applet will occupy
on the web page. Applets are not resizeable (except when run with the
appletview application. But if you're using appletviewer,
why are you writing an applet?
code="Xxxx.class"
code="yourPackage.Xxxx.class" archive="yourPackage.jar"
<applet code="mousedemo.MouseTest.class" archive="mousedemo.jar" width="400" height="200"></applet>