📕 Module IV: AWT, Layout Management and Event Handling, Swing ( By
Santosh )
● Applet Life Cycle
● Running Applets
● Methods of Applet Class
● Graphics Class
○ Color Class
○ Font Class
● Limitations of Applets
● Interfaces of Java AWT
● Layout Management
○ FlowLayout
○ BorderLayout
○ GridLayout
● Event Delegation Model
○ Event Classes
○ Event Listener Interfaces
● Introduction to Swing
○ Differences between AWT and Swing
○ Creating Simple Applications using Swing
○ Commonly used Swing Components: JLabel, JTextField, JButton,
JCheckBox, JRadioButton, JComboBox, etc.
1. Applet Life Cycle
An applet is a small Java program that runs inside a web browser or applet viewer. It has a
special life cycle — a series of methods called automatically by the system to control its
behavior.
Life Cycle Methods:
Method When It Runs Purpose
init() Once, when applet is loaded Initialize variables or setup UI
start() After init() and when applet restarts Start animations or actions
paint() Whenever applet needs to redraw itself Draw graphics or text on screen
stop() When applet is hidden or stopped Pause animations or free
resources
destroy When applet is about to be destroyed Cleanup before unloading
()
Example:
import java.applet.Applet;
import java.awt.Graphics;
public class SimpleApplet extends Applet {
public void init() {
System.out.println("Applet initialized");
}
public void start() {
System.out.println("Applet started");
}
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 20, 20);
}
public void stop() {
System.out.println("Applet stopped");
}
public void destroy() {
System.out.println("Applet destroyed");
}
}
2. Running Applets
● Traditionally, applets run inside a web browser using an HTML <applet> tag.
● Since browsers don’t support Java applets anymore, we use appletviewer, a tool that
comes with JDK, to run applets.
HTML Example:
<applet code="SimpleApplet.class" width="300" height="100"></applet>
● code specifies the compiled applet class.
● width and height set the applet size.
3. Methods of Applet Class
Some useful applet methods:
● getParameter(String name): Reads parameters passed from HTML. For example,
to pass user name to applet.
● resize(int width, int height): Changes applet size dynamically.
● showStatus(String msg): Displays a message on the browser's status bar (not
always visible nowadays).
4. Graphics Class
This class helps you draw shapes, images, and text on screen inside paint() method.
Important Methods:
● drawLine(int x1, int y1, int x2, int y2): Draw a line between two points.
● drawRect(int x, int y, int width, int height): Draw a rectangle outline.
● fillRect(int x, int y, int width, int height): Draw a filled rectangle.
● drawOval(int x, int y, int width, int height): Draw an oval inside the
specified rectangle.
● drawString(String str, int x, int y): Draw text starting at (x,y).
● setColor(Color c): Change drawing color.
● setFont(Font f): Set the font for text.
Example:
public void paint(Graphics g) {
g.setColor(Color.BLUE);
g.drawString("Welcome!", 50, 50);
g.drawRect(40, 60, 100, 50);
g.fillOval(40, 120, 100, 50);
}
5. Color Class
Represents colors in RGB format (Red, Green, Blue), values 0 to 255.
● You can use predefined colors: Color.RED, Color.GREEN, Color.BLUE, etc.
● Or create your own:
Color myColor = new Color(255, 200, 100); // Custom orange shade
6. Font Class
Used to specify the font style when drawing text.
Font font = new Font("Arial", Font.BOLD, 18);
g.setFont(font);
g.drawString("Bold Text", 50, 100);
● Common styles: Font.PLAIN, Font.BOLD, Font.ITALIC
● You specify the font name, style, and size.
7. Limitations of Applets
● Security Restrictions: Cannot read/write files on user’s computer or connect to
arbitrary network locations (only the server they came from).
● Browser Support: Most modern browsers no longer support Java plugins.
● Performance: Not suitable for heavy or complex applications.
● UI Controls: Limited user interface components compared to desktop applications.
Because of these limitations, applets are mostly obsolete now and replaced by technologies like
Java Web Start or web frameworks.
8. Interfaces of Java AWT
Java AWT provides many interfaces that components implement to handle user events:
● ActionListener: Handles actions like button clicks.
● MouseListener: Handles mouse events (click, enter, exit).
● KeyListener: Handles keyboard events.
● WindowListener: Handles window events (open, close, minimize).
9. Layout Management
Layout managers control how components (buttons, text fields) are arranged inside containers
(Frames, Panels).
Why use layout managers?
● To arrange components automatically regardless of screen size.
● Avoid manual pixel positioning, which is inflexible.
9.1 FlowLayout
● Default for Panel.
● Places components in a row, left to right.
● Wraps to next line if no space.
● Can be aligned left, center, or right.
setLayout(new FlowLayout(FlowLayout.LEFT));
9.2 BorderLayout
● Divides container into 5 regions: North, South, East, West, Center.
● Each region holds one component.
● Center takes remaining space.
setLayout(new BorderLayout());
add(button1, BorderLayout.NORTH);
add(button2, BorderLayout.CENTER);
9.3 GridLayout
● Organizes components in a grid with equal cells.
● You specify rows and columns.
setLayout(new GridLayout(2, 3)); // 2 rows, 3 columns
10. Event Delegation Model
Java uses Event Delegation Model for handling events. It means:
● The source object (like a button) generates an event.
● The event is passed to an event object (e.g., ActionEvent).
● The event is delivered to one or more listener objects registered to handle the event.
● The listener handles the event in a callback method.
This model improves efficiency by separating event generation and handling, and lets multiple
listeners react to the same event.
11. Event Classes
Some important event classes:
● ActionEvent: Generated when a button is clicked.
● MouseEvent: Generated by mouse actions (click, move).
● KeyEvent: Keyboard key pressed or released.
● WindowEvent: Window actions like closing or minimizing.
12. Event Listener Interfaces
These interfaces declare methods that handle specific events.
Interface Purpose Key Method(s)
ActionListe Handle button clicks and similar actions actionPerformed(ActionEve
ner nt e)
MouseListen Handle mouse events mouseClicked, mouseEntered,
er etc.
KeyListener Handle keyboard input keyPressed, keyReleased,
etc.
WindowListe Handle window events windowClosing,
ner windowOpened, etc.
13. Introduction to Swing
Swing is a Java GUI toolkit that provides a rich set of lightweight components.
● It’s part of Java Foundation Classes (JFC).
● Swing components look the same on all platforms (cross-platform).
● Supports pluggable look-and-feel.
● Extends AWT functionality with more advanced components.
14. Differences between AWT and Swing
Feature AWT Swing
Components Heavyweight (uses native OS UI) Lightweight (pure Java)
Look & Feel Platform-dependent Pluggable, consistent across
OS
Components Variety Basic Rich & advanced (tables, trees)
Event Model Older, less flexible More advanced and flexible
Customization Limited Highly customizable
15. Creating Simple Applications Using Swing
Basic Swing application uses JFrame as main window.
Simple Swing Example:
import javax.swing.*;
public class SimpleSwingApp {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Swing App");
JButton button = new JButton("Click Me");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(button); // Add button to frame
frame.setVisible(true); // Show window
}
}
16. Commonly Used Swing Components
Component Purpose
JLabel Displays non-editable text/images
JTextField Single-line input text field
JButton Push button to trigger actions
JCheckBox Checkbox for true/false options
JRadioButt Mutually exclusive selection (in groups)
on
JComboBox Drop-down list to select one item
Example: Using JLabel, JTextField and JButton
import javax.swing.*;
import java.awt.event.*;
public class SwingExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Components");
frame.setSize(400, 200);
frame.setLayout(null); // Using absolute positioning here for
simplicity
JLabel label = new JLabel("Enter Name:");
label.setBounds(50, 30, 100, 20);
JTextField textField = new JTextField();
textField.setBounds(150, 30, 150, 20);
JButton button = new JButton("Submit");
button.setBounds(150, 70, 100, 30);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Hello " +
textField.getText());
}
});
frame.add(label);
frame.add(textField);
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}