Java Applets - Lecture Notes
1. Applet Basics
- An Applet is a Java program that runs in a web browser or applet viewer. - Unlike standalone
applications, applets do not require a main() method. - Applets are typically used for creating
interactive features for web applications. - They extend the [Link] class and override its
lifecycle methods.
2. Applet Architecture
- Applet architecture is based on a lifecycle managed by the browser or applet viewer. - Important
lifecycle methods: • init(): Called once for initialization. • start(): Called each time the applet is
started. • stop(): Called when the user leaves the page. • destroy(): Called just before the applet is
terminated. - The Applet class is a subclass of the AWT Panel class, which allows GUI elements.
3. Applet Skeleton
A basic skeleton of an applet: import [Link]; import [Link]; public class
MyApplet extends Applet { public void init() { // initialization code } public void start() { // start code }
public void stop() { // stop code } public void destroy() { // cleanup code } public void paint(Graphics
g) { [Link]("Hello Applet", 20, 20); } }
4. Applet Display Method
- The display of output in an applet is handled by the paint(Graphics g) method. - It is automatically
called whenever the applet needs to be redrawn. - Example: [Link]("Message", x, y); - The
repaint() method can be used to refresh the applet, which calls update() and then paint().
5. Requesting Repainting
- repaint() is used to request a redraw of the applet. - When repaint() is called, update(Graphics g)
is executed, which clears the background and then calls paint(). - Useful for dynamic or animated
graphics.
6. HTML Tag
- Applets are embedded in HTML documents using the tag. - Syntax: - Attributes: • code: Name of
the compiled .class file • width, height: Size of the display area • align, alt, name: Optional attributes
- (Note: In modern Java, is deprecated.)
7. Passing Parameters to an Applet
- Parameters are passed using inside the APPLET tag. - Example: - The applet can retrieve
parameter values using getParameter("name").
8. Layout Managers
- Layout managers control the positioning of components inside an applet. - Common layout
managers: • FlowLayout: Places components left to right, wrapping to next line. • BorderLayout:
Divides container into five regions (N, S, E, W, Center). • GridLayout: Divides container into
equal-sized cells. - Example: setLayout(new FlowLayout());