[Go to site: main page, start]

0% found this document useful (0 votes)
9 views28 pages

Java Applets: Basics, Lifecycle & Graphics

The document provides an overview of Java applets, detailing their characteristics, architecture, lifecycle, creation process, parameter passing, graphics capabilities, and important classes. It explains the differences between applets and applications, outlines the applet lifecycle methods, and describes how to create and run applets using HTML. Additionally, it covers AWT components, layout managers, and examples of drawing various shapes and handling multimedia in applets.

Uploaded by

intern.alpha.ge
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views28 pages

Java Applets: Basics, Lifecycle & Graphics

The document provides an overview of Java applets, detailing their characteristics, architecture, lifecycle, creation process, parameter passing, graphics capabilities, and important classes. It explains the differences between applets and applications, outlines the applet lifecycle methods, and describes how to create and run applets using HTML. Additionally, it covers AWT components, layout managers, and examples of drawing various shapes and handling multimedia in applets.

Uploaded by

intern.alpha.ge
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Applets, AWT & Swing

1. APPLET BASICS
What is an Applet?

An applet is a Java program that runs within a web browser or applet viewer. It is embedded
in an HTML page and executed on the client side.

Key Characteristics:

 Platform Independent: Runs on any system with JVM


 Secure: Runs in a sandbox environment with restricted access
 Embedded: Integrated into HTML pages using <applet> tag
 Downloaded: Transferred from server to client automatically
 No main() method: Uses init(), start(), stop(), destroy() methods

Applet vs Application:

Feature Applet Application


Entry Point init() method main() method
Execution Browser/Applet Viewer Standalone
GUI Automatic Manual creation needed
Security Restricted (sandbox) Full access

2. APPLET ARCHITECTURE
Inheritance Hierarchy:
[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

Core Components:

1. [Link]: Base class for all applets


2. [Link]: Provides GUI capabilities
3. [Link]: Can contain other components
4. AppletContext: Interface for browser environment
5. AppletStub: Interface connecting applet to browser

1
Applet Execution Environment:

 Browser: Provides runtime environment


 Applet Viewer: Testing tool from JDK
 Security Manager: Controls applet permissions
 Class Loader: Loads applet classes dynamically

3. LIFECYCLE OF JAVA APPLETS


Five Key Methods:

1. init()

 Called once when applet is first loaded


 Used for initialization tasks
 Setup variables, load images, set background color

public void init() {


setBackground([Link]);
// Initialization code
}

2. start()

 Called after init() and whenever applet becomes active


 Starts or resumes threads
 Called when user returns to the page

public void start() {


// Start animations or threads
}

3. paint(Graphics g)

 Called to render applet display


 Automatically invoked after init() and start()
 Can be explicitly called using repaint()

public void paint(Graphics g) {


[Link]("Hello Applet", 50, 50);
}

4. stop()

 Called when user leaves the page


 Suspends threads or animations
 Releases resources temporarily

public void stop() {

2
// Suspend threads
}

5. destroy()

 Called when applet is being removed permanently


 Final cleanup
 Release all resources

public void destroy() {


// Final cleanup code
}

Lifecycle Flow:
Applet Loaded → init() → start() → paint()

User leaves page → stop()

User returns → start() → paint()

Browser closes → destroy()

4. CREATION OF APPLETS
Step 1: Write Applet Code
import [Link];
import [Link];

public class MyApplet extends Applet {


public void paint(Graphics g) {
[Link]("Welcome to Applets!", 20, 30);
}
}

Step 2: Compile the Applet


javac [Link]

Step 3: Create HTML File


<html>
<head>
<title>My Applet</title>
</head>
<body>
<applet code="[Link]" width="400" height="300">
Your browser does not support applets.
</applet>
</body>
</html>

3
Step 4: Run the Applet

 Using Browser: Open HTML file


 Using Applet Viewer: appletviewer [Link]

Important Notes:

 Applets don't have main() method


 Must extend Applet or JApplet class
 .class file must be in same directory as HTML
 Use paint() method for drawing

5. PARAMETER PASSING TO APPLETS


Passing Parameters from HTML:
<applet code="[Link]" width="400" height="300">
<param name="message" value="Hello World">
<param name="fontSize" value="20">
<param name="color" value="blue">
</applet>

Retrieving Parameters in Applet:


import [Link];
import [Link];
import [Link];
import [Link];

public class ParamApplet extends Applet {


String message;
int fontSize;
Color textColor;

public void init() {


// Get parameter values
message = getParameter("message");

String sizeStr = getParameter("fontSize");


fontSize = [Link](sizeStr);

String colorStr = getParameter("color");


if([Link]("blue"))
textColor = [Link];
else
textColor = [Link];
}

public void paint(Graphics g) {


[Link](textColor);
[Link](new Font("Arial", [Link], fontSize));
[Link](message, 50, 50);
}

4
}

Key Methods:

 getParameter(String name): Returns parameter value as String


 Returns null if parameter not found
 Always returns String, conversion needed for other types

6. APPLET GRAPHICS
Graphics Class Methods:

Drawing Methods:

1. drawLine(int x1, int y1, int x2, int y2): Draws a line
2. drawRect(int x, int y, int width, int height): Draws rectangle outline
3. fillRect(int x, int y, int width, int height): Draws filled rectangle
4. drawOval(int x, int y, int width, int height): Draws oval outline
5. fillOval(int x, int y, int width, int height): Draws filled oval
6. drawArc(int x, int y, int w, int h, int start, int arc): Draws arc
7. fillArc(int x, int y, int w, int h, int start, int arc): Draws filled arc
8. drawPolygon(int[] x, int[] y, int points): Draws polygon
9. fillPolygon(int[] x, int[] y, int points): Draws filled polygon
10. drawString(String str, int x, int y): Draws text

Color and Font Methods:

 setColor(Color c): Sets drawing color


 setFont(Font f): Sets text font
 getColor(): Gets current color
 getFont(): Gets current font

Examples:

Example 1: Drawing Lines

import [Link];
import [Link];
import [Link];

public class LineApplet extends Applet {


public void paint(Graphics g) {
// Horizontal line
[Link](10, 20, 200, 20);

// Vertical line
[Link]([Link]);
[Link](50, 10, 50, 150);

// Diagonal line

5
[Link]([Link]);
[Link](10, 10, 200, 150);
}
}

Example 2: Drawing Rectangles

import [Link];
import [Link];
import [Link];

public class RectangleApplet extends Applet {


public void paint(Graphics g) {
// Outline rectangle
[Link](10, 10, 100, 50);

// Filled rectangle
[Link]([Link]);
[Link](120, 10, 100, 50);

// Rounded rectangle
[Link]([Link]);
[Link](10, 80, 100, 50, 20, 20);
}
}

Example 3: Drawing Ovals and Circles

import [Link];
import [Link];
import [Link];

public class OvalApplet extends Applet {


public void paint(Graphics g) {
// Oval outline
[Link](10, 10, 150, 80);

// Filled circle (width = height)


[Link]([Link]);
[Link](200, 10, 100, 100);

// Filled oval
[Link]([Link]);
[Link](50, 120, 200, 100);
}
}

Example 4: Drawing Polygons

import [Link];
import [Link];
import [Link];

public class PolygonApplet extends Applet {


public void paint(Graphics g) {
// Triangle
int[] xTriangle = {100, 150, 50};
int[] yTriangle = {50, 150, 150};
[Link](xTriangle, yTriangle, 3);

6
// Pentagon
int[] xPenta = {250, 300, 280, 220, 200};
int[] yPenta = {50, 80, 130, 130, 80};
[Link]([Link]);
[Link](xPenta, yPenta, 5);

// Hexagon
int[] xHexa = {400, 450, 450, 400, 350, 350};
int[] yHexa = {50, 75, 125, 150, 125, 75};
[Link]([Link]);
[Link](xHexa, yHexa, 6);
}
}

Example 5: Drawing Arcs

import [Link];
import [Link];
import [Link];

public class ArcApplet extends Applet {


public void paint(Graphics g) {
// Semi-circle (180 degrees)
[Link](10, 10, 100, 100, 0, 180);

// Quarter circle (90 degrees)


[Link]([Link]);
[Link](150, 10, 100, 100, 0, 90);

// Pac-man shape
[Link]([Link]);
[Link](300, 10, 100, 100, 45, 270);
}
}

7. APPLET CLASSES
Important Applet Classes:

1. [Link]

 Base class for all applets


 Provides lifecycle methods
 Key Methods:
o init(), start(), stop(), destroy()
o getParameter(String name)
o getAppletContext()
o getCodeBase(), getDocumentBase()
o showStatus(String msg)
o play(URL url) - plays audio clip
o getImage(URL url, String name) - loads image

2. [Link]

7
 Represents applet's environment (browser)
 Methods:
o getApplet(String name)
o getApplets()
o showDocument(URL url)
o showStatus(String status)

3. [Link]

 Interface between applet and browser


 Methods:
o isActive()
o getDocumentBase()
o getCodeBase()
o getParameter(String name)
o appletResize(int width, int height)

4. [Link]

 Represents audio clip


 Methods:
o play() - plays audio once
o loop() - plays audio repeatedly
o stop() - stops playing

Example Using Multiple Classes:


import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class MultiMediaApplet extends Applet {


Image img;
AudioClip clip;

public void init() {


try {
URL imgURL = new URL(getCodeBase(), "[Link]");
img = getImage(imgURL);

URL audioURL = new URL(getCodeBase(), "[Link]");


clip = getAudioClip(audioURL);
} catch(Exception e) {
showStatus("Error loading resources");
}
}

public void start() {


if(clip != null)
[Link]();
}

public void stop() {


if(clip != null)
[Link]();

8
}

public void paint(Graphics g) {


if(img != null)
[Link](img, 10, 10, this);
}
}

8. AWT COMPONENTS AND CONTAINERS


AWT (Abstract Window Toolkit)

Platform-independent GUI framework for Java applications and applets.

Component Hierarchy:
Component (Abstract Class)
├── Button
├── Canvas
├── Checkbox
├── Choice
├── Label
├── List
├── Scrollbar
├── TextComponent
│ ├── TextArea
│ └── TextField
└── Container
├── Panel
│ └── Applet
├── Window
│ ├── Frame
│ └── Dialog
└── ScrollPane

Common AWT Components:

1. Button

Button btn = new Button("Click Me");


add(btn);

2. Label

Label lbl = new Label("Enter Name:");


add(lbl);

3. TextField

TextField txt = new TextField(20); // 20 columns


add(txt);

4. TextArea

9
TextArea area = new TextArea(5, 30); // 5 rows, 30 columns
add(area);

5. Checkbox

Checkbox cb1 = new Checkbox("Java");


Checkbox cb2 = new Checkbox("Python");
add(cb1);
add(cb2);

6. CheckboxGroup (Radio Buttons)

CheckboxGroup group = new CheckboxGroup();


Checkbox male = new Checkbox("Male", group, true);
Checkbox female = new Checkbox("Female", group, false);
add(male);
add(female);

7. Choice (Dropdown)

Choice choice = new Choice();


[Link]("Red");
[Link]("Green");
[Link]("Blue");
add(choice);

8. List

List list = new List(4, true); // 4 visible rows, multiple selection


[Link]("Item 1");
[Link]("Item 2");
[Link]("Item 3");
add(list);

9. Scrollbar

Scrollbar scroll = new Scrollbar([Link], 0, 10, 0, 100);


add(scroll);

Container Classes:

1. Panel

 Generic container
 Default layout: FlowLayout

Panel panel = new Panel();


[Link](new Button("Button 1"));
[Link](new Button("Button 2"));
add(panel);

2. Frame

 Top-level window with title and border

10
Frame frame = new Frame("My Window");
[Link](400, 300);
[Link](true);

3. Dialog

 Pop-up window

Dialog dialog = new Dialog(frame, "Dialog Box", true);


[Link](200, 150);
[Link](true);

4. ScrollPane

 Container with automatic scrollbars

ScrollPane pane = new ScrollPane();


[Link](new Button("Large Button"));
add(pane);

9. LAYOUT MANAGERS
Layout managers control the size and position of components in containers.

1. FlowLayout

 Default for Panel and Applet


 Arranges components left-to-right, top-to-bottom

setLayout(new FlowLayout());
// or
setLayout(new FlowLayout([Link], 10, 20));
// alignment, hgap, vgap

Alignment Options: LEFT, RIGHT, CENTER, LEADING, TRAILING

2. BorderLayout

 Default for Frame and Dialog


 Five regions: NORTH, SOUTH, EAST, WEST, CENTER

setLayout(new BorderLayout());
add(new Button("North"), [Link]);
add(new Button("South"), [Link]);
add(new Button("East"), [Link]);
add(new Button("West"), [Link]);
add(new Button("Center"), [Link]);

3. GridLayout

 Arranges components in rows and columns

11
 All cells are equal size

setLayout(new GridLayout(3, 2)); // 3 rows, 2 columns


// or
setLayout(new GridLayout(3, 2, 5, 5)); // with gaps

4. CardLayout

 Shows one component at a time (like tabs)

CardLayout card = new CardLayout();


setLayout(card);
Panel p1 = new Panel();
Panel p2 = new Panel();
add(p1, "Card1");
add(p2, "Card2");
[Link](this, "Card1");

Methods: first(), last(), next(), previous(), show()

5. GridBagLayout

 Most flexible and complex


 Components can span multiple rows/columns

GridBagLayout gbl = new GridBagLayout();


GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbl);

[Link] = 0;
[Link] = 0;
[Link] = 2;
Button btn = new Button("Wide Button");
add(btn, gbc);

Comparison:

Layout Use Case Flexibility


FlowLayout Simple, sequential Low
BorderLayout Five-region design Medium
GridLayout Uniform grid Medium
CardLayout Multiple views Medium
GridBagLayout Complex forms High

10. LISTENERS AND ADAPTER CLASSES


Event Listener Interfaces:

1. ActionListener

 For buttons, menu items, text fields


12
public interface ActionListener extends EventListener {
void actionPerformed(ActionEvent e);
}

Usage:

Button btn = new Button("Click");


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button clicked");
}
});

2. MouseListener

 Five methods for mouse events

public interface MouseListener extends EventListener {


void mouseClicked(MouseEvent e);
void mousePressed(MouseEvent e);
void mouseReleased(MouseEvent e);
void mouseEntered(MouseEvent e);
void mouseExited(MouseEvent e);
}

3. MouseMotionListener

public interface MouseMotionListener extends EventListener {


void mouseDragged(MouseEvent e);
void mouseMoved(MouseEvent e);
}

4. KeyListener

public interface KeyListener extends EventListener {


void keyTyped(KeyEvent e);
void keyPressed(KeyEvent e);
void keyReleased(KeyEvent e);
}

5. WindowListener

public interface WindowListener extends EventListener {


void windowOpened(WindowEvent e);
void windowClosing(WindowEvent e);
void windowClosed(WindowEvent e);
void windowIconified(WindowEvent e);
void windowDeiconified(WindowEvent e);
void windowActivated(WindowEvent e);
void windowDeactivated(WindowEvent e);
}

6. ItemListener

 For checkbox, choice, list

13
public interface ItemListener extends EventListener {
void itemStateChanged(ItemEvent e);
}

7. TextListener

 For text components

public interface TextListener extends EventListener {


void textValueChanged(TextEvent e);
}

Adapter Classes:

Adapter classes provide empty implementations of listener interfaces with multiple methods.

1. MouseAdapter

public abstract class MouseAdapter implements MouseListener {


public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}

Usage:

addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// Only override needed method
}
});

2. MouseMotionAdapter

addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
// Handle drag only
}
});

3. KeyAdapter

addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// Handle key press only
}
});

4. WindowAdapter

[Link](new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);

14
}
});

5. FocusAdapter

addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent e) {
// Handle focus gain
}
});

Adapter Classes Available:

 ComponentAdapter
 ContainerAdapter
 FocusAdapter
 KeyAdapter
 MouseAdapter
 MouseMotionAdapter
 WindowAdapter

Note: Adapter classes don't exist for ActionListener, ItemListener, TextListener (only one
method each).

11. EVENT DELEGATION MODEL


Overview:

The Event Delegation Model (introduced in Java 1.1) separates event sources from event
handlers.

Key Concepts:

1. Event Source

 Component that generates the event (Button, TextField, etc.)


 Maintains list of listeners
 Fires events to registered listeners

2. Event Object

 Contains information about the event


 Extends [Link]
 Examples: ActionEvent, MouseEvent, KeyEvent

3. Event Listener

 Object that receives event notifications

15
 Implements specific listener interface
 Registered with event source

Event Flow:
User Action → Event Source → Event Object → Event Listener → Handler Method

Registration Methods:
 addActionListener()
 addMouseListener()
 addKeyListener()
 addWindowListener()
 etc.

Example:
import [Link];
import [Link].*;
import [Link].*;

public class EventDemo extends Applet implements ActionListener {


Button btn;
TextField txt;

public void init() {


btn = new Button("Click Me");
txt = new TextField(20);

// Register listener
[Link](this);

add(btn);
add(txt);
}

// Event handler
public void actionPerformed(ActionEvent e) {
if([Link]() == btn) {
[Link]("Button was clicked!");
}
}
}

Event Classes Hierarchy:


[Link]

[Link]
├── ActionEvent
├── ItemEvent
├── TextEvent
├── ComponentEvent
│ ├── InputEvent
│ │ ├── KeyEvent
│ │ └── MouseEvent
│ ├── FocusEvent

16
│ ├── WindowEvent
│ └── ContainerEvent
└── AdjustmentEvent

Advantages:

1. Separation of concerns: UI and logic separated


2. Multiple listeners: One source can have many listeners
3. Flexibility: Listeners can be added/removed dynamically
4. Type safety: Compile-time checking
5. No event propagation: Events sent only to registered listeners

Inner Class Approach:


public class InnerDemo extends Applet {
Button btn;

public void init() {


btn = new Button("Click");
[Link](new ButtonHandler());
add(btn);
}

// Inner class
class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
showStatus("Button clicked!");
}
}
}

Anonymous Inner Class:


[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
showStatus("Button clicked!");
}
});

12. SWING: INTRODUCTION


What is Swing?

 Advanced GUI toolkit built on top of AWT


 Part of Java Foundation Classes (JFC)
 Provides richer set of components
 Lightweight components (written in Java)

Swing vs AWT:

Feature AWT Swing


Components Heavy-weight Light-weight

17
Feature AWT Swing
Platform Platform-dependent Platform-independent
Look & Feel Native OS Pluggable
Components Limited Extensive
MVC No Yes
Performance Faster Slightly slower

Swing Component Hierarchy:


[Link]

[Link]

[Link]

[Link] (Abstract)
├── JButton
├── JLabel
├── JTextField
├── JTextArea
├── JCheckBox
├── JRadioButton
├── JComboBox
├── JList
├── JTable
├── JTree
├── JPanel
├── JScrollPane
├── JMenuBar
├── JMenu
├── JMenuItem
└── ... (many more)

Swing Component Classes:

Basic Components:

1. JLabel

JLabel label = new JLabel("Enter Name:");


[Link](new Font("Arial", [Link], 14));

2. JButton

JButton btn = new JButton("Submit");


[Link]("Click to submit");

3. JTextField

JTextField txt = new JTextField(20);


[Link]("Default text");

4. JTextArea

18
JTextArea area = new JTextArea(5, 20);
JScrollPane scroll = new JScrollPane(area);

5. JCheckBox

JCheckBox cb = new JCheckBox("Accept Terms", true);

6. JRadioButton

JRadioButton male = new JRadioButton("Male");


JRadioButton female = new JRadioButton("Female");
ButtonGroup group = new ButtonGroup();
[Link](male);
[Link](female);

7. JComboBox

String[] items = {"Java", "Python", "C++"};


JComboBox<String> combo = new JComboBox<>(items);

8. JList

String[] data = {"Item 1", "Item 2", "Item 3"};


JList<String> list = new JList<>(data);

9. JPasswordField

JPasswordField pwd = new JPasswordField(15);


char[] password = [Link]();

10. JSlider

JSlider slider = new JSlider(0, 100, 50);


[Link](20);
[Link](true);
[Link](true);

Swing Container Classes:

1. JFrame

 Top-level window

JFrame frame = new JFrame("My Application");


[Link](400, 300);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);

2. JPanel

 Generic container

JPanel panel = new JPanel();


[Link](new FlowLayout());

19
[Link](new JButton("Button"));

3. JDialog

 Modal or non-modal dialog

JDialog dialog = new JDialog(frame, "Dialog", true);


[Link](300, 200);
[Link](true);

4. JScrollPane

 Adds scrollbars to components

JTextArea area = new JTextArea(10, 30);


JScrollPane scroll = new JScrollPane(area);

5. JTabbedPane

 Tabbed interface

JTabbedPane tabs = new JTabbedPane();


[Link]("Tab 1", panel1);
[Link]("Tab 2", panel2);

6. JSplitPane

 Divides two components

JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,


leftPanel, rightPanel);

7. JToolBar

 Movable toolbar

JToolBar toolbar = new JToolBar();


[Link](new JButton("New"));
[Link](new JButton("Open"));

Menu Components:

JMenuBar, JMenu, JMenuItem

JMenuBar menuBar = new JMenuBar();


JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
JMenuItem exitItem = new JMenuItem("Exit");

[Link](openItem);
[Link]();
[Link](exitItem);
[Link](fileMenu);

20
[Link](menuBar);

Swing Features:

1. Look and Feel

// Set to system look and feel


[Link](
[Link]()
);

// Set to cross-platform (Metal)


[Link](
[Link]()
);

2. Borders

[Link]([Link]("Title"));
[Link]([Link]([Link]));
[Link]([Link]());

3. Icons and Images

ImageIcon icon = new ImageIcon("[Link]");


JLabel label = new JLabel("Text with icon", icon, [Link]);
JButton btn = new JButton("Button", icon);

4. ToolTips

[Link]("Click here to submit");

5. Mnemonics and Accelerators

// Alt+F to open menu


[Link](KeyEvent.VK_F);

// Ctrl+O for menu item


[Link]([Link](
KeyEvent.VK_O, ActionEvent.CTRL_MASK));

Complete Swing Application Example:


import [Link].*;
import [Link].*;
import [Link].*;

public class SwingDemo extends JFrame implements ActionListener {


JTextField nameField;
JButton submitBtn;
JLabel resultLabel;

public SwingDemo() {
setTitle("Swing Application");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

21
setLayout(new FlowLayout());

// Components
JLabel nameLabel = new JLabel("Enter Name:");
nameField = new JTextField(20);
submitBtn = new JButton("Submit");
resultLabel = new JLabel("");

// Event handling
[Link](this);

// Add to frame
add(nameLabel);
add(nameField);
add(submitBtn);
add(resultLabel);

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String name = [Link]();
[Link]("Hello, " + name + "!");
}

public static void main(String[] args) {


new SwingDemo();
}
}

JApplet Example:
import [Link].*;
import [Link].*;
import [Link].*;

public class SwingAppletDemo extends JApplet implements ActionListener {


JButton btn;
JTextField txt;

public void init() {


// Use content pane for JApplet
Container c = getContentPane();
[Link](new FlowLayout());

btn = new JButton("Click Me");


txt = new JTextField(20);

[Link](this);

[Link](btn);
[Link](txt);
}

public void actionPerformed(ActionEvent e) {


[Link]("Button clicked in JApplet!");
}
}

Key Differences in JApplet:


22
1. Extends JApplet instead of Applet
2. Use getContentPane() to add components
3. Supports all Swing components
4. Better appearance and functionality

Swing Event Handling:

 Uses same event delegation model as AWT


 Same listener interfaces
 Same adapter classes
 Additional Swing-specific events

Advantages of Swing:

1. Platform Independence: Pure Java implementation


2. Rich Components: More components than AWT
3. Customizable: Pluggable look and feel
4. Lightweight: Better performance in many cases
5. MVC Architecture: Better design pattern
6. Enhanced Features: Tooltips, borders, icons
7. Double Buffering: Reduces flickering

Disadvantages of Swing:

1. Complexity: More complex than AWT


2. Performance: Can be slower for simple applications
3. Learning Curve: More classes and concepts
4. Older Technology: JavaFX is newer alternative

13. PRACTICAL EXAMPLES


Example 1: Complete Applet with Graphics
import [Link];
import [Link].*;
import [Link].*;

public class DrawingApplet extends Applet implements MouseListener {


int x, y;
boolean hasPoint = false;

public void init() {


setBackground([Link]);
addMouseListener(this);
}

public void paint(Graphics g) {


// Draw coordinate system
[Link]([Link]);
[Link](0, getHeight()/2, getWidth(), getHeight()/2);

23
[Link](getWidth()/2, 0, getWidth()/2, getHeight());

// Draw shapes
[Link]([Link]);
[Link](50, 50, 80, 80);

[Link]([Link]);
[Link](200, 50, 100, 60);

[Link]([Link]);
int[] xPoints = {350, 400, 300};
int[] yPoints = {50, 110, 110};
[Link](xPoints, yPoints, 3);

// Draw clicked point


if(hasPoint) {
[Link]([Link]);
[Link](x-5, y-5, 10, 10);
[Link]("(" + x + ", " + y + ")", x+10, y-10);
}
}

public void mouseClicked(MouseEvent e) {


x = [Link]();
y = [Link]();
hasPoint = true;
repaint();
}

public void mousePressed(MouseEvent e) {}


public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}

Example 2: AWT Application with Multiple Layouts


import [Link].*;
import [Link].*;

public class LayoutDemo extends Frame {


public LayoutDemo() {
setTitle("Layout Manager Demo");
setSize(500, 400);
setLayout(new BorderLayout());

// North panel with FlowLayout


Panel northPanel = new Panel();
[Link](new FlowLayout());
[Link](new Button("Button 1"));
[Link](new Button("Button 2"));
[Link](new Button("Button 3"));

// Center panel with GridLayout


Panel centerPanel = new Panel();
[Link](new GridLayout(3, 3, 5, 5));
for(int i = 1; i <= 9; i++) {
[Link](new Button("" + i));
}

24
// South panel
Panel southPanel = new Panel();
[Link](new Label("Status: Ready"));

// East panel
Panel eastPanel = new Panel();
[Link](new GridLayout(4, 1, 5, 5));
[Link](new Button("Up"));
[Link](new Button("Down"));
[Link](new Button("Left"));
[Link](new Button("Right"));

// Add to frame
add(northPanel, [Link]);
add(centerPanel, [Link]);
add(southPanel, [Link]);
add(eastPanel, [Link]);

// Window closing
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});

setVisible(true);
}

public static void main(String[] args) {


new LayoutDemo();
}
}

Example 3: Swing Registration Form


import [Link].*;
import [Link].*;
import [Link].*;

public class RegistrationForm extends JFrame implements ActionListener {


JTextField nameField, emailField;
JPasswordField passwordField;
JRadioButton maleBtn, femaleBtn;
JCheckBox termsBox;
JComboBox<String> countryBox;
JTextArea displayArea;
JButton submitBtn, clearBtn;

public RegistrationForm() {
setTitle("Registration Form");
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Main panel
JPanel mainPanel = new JPanel();
[Link](new GridLayout(8, 2, 10, 10));
[Link]([Link](10, 10, 10,
10));

25
// Name
[Link](new JLabel("Name:"));
nameField = new JTextField();
[Link](nameField);

// Email
[Link](new JLabel("Email:"));
emailField = new JTextField();
[Link](emailField);

// Password
[Link](new JLabel("Password:"));
passwordField = new JPasswordField();
[Link](passwordField);

// Gender
[Link](new JLabel("Gender:"));
JPanel genderPanel = new JPanel(new FlowLayout([Link]));
maleBtn = new JRadioButton("Male");
femaleBtn = new JRadioButton("Female");
ButtonGroup genderGroup = new ButtonGroup();
[Link](maleBtn);
[Link](femaleBtn);
[Link](maleBtn);
[Link](femaleBtn);
[Link](genderPanel);

// Country
[Link](new JLabel("Country:"));
String[] countries = {"India", "USA", "UK", "Canada", "Australia"};
countryBox = new JComboBox<>(countries);
[Link](countryBox);

// Terms
[Link](new JLabel(""));
termsBox = new JCheckBox("I accept terms and conditions");
[Link](termsBox);

// Buttons
[Link](new JLabel(""));
JPanel btnPanel = new JPanel(new FlowLayout([Link]));
submitBtn = new JButton("Submit");
clearBtn = new JButton("Clear");
[Link](this);
[Link](this);
[Link](submitBtn);
[Link](clearBtn);
[Link](btnPanel);

// Display area
displayArea = new JTextArea(8, 40);
[Link](false);
JScrollPane scrollPane = new JScrollPane(displayArea);
[Link]([Link]("Registration
Details"));

// Add to frame
add(mainPanel, [Link]);
add(scrollPane, [Link]);

setVisible(true);

26
}

public void actionPerformed(ActionEvent e) {


if([Link]() == submitBtn) {
if(![Link]()) {
[Link](this,
"Please accept terms and conditions!");
return;
}

StringBuilder sb = new StringBuilder();


[Link]("Name: ").append([Link]()).append("\n");
[Link]("Email: ").append([Link]()).append("\n");
[Link]("Gender: ");
[Link]([Link]() ? "Male" : "Female").append("\
n");
[Link]("Country:
").append([Link]()).append("\n");

[Link]([Link]());
[Link](this, "Registration
Successful!");

} else if([Link]() == clearBtn) {


[Link]("");
[Link]("");
[Link]("");
[Link](false);
[Link](false);
[Link](false);
[Link](0);
[Link]("");
}
}

public static void main(String[] args) {


new RegistrationForm();
}
}

10 IMPORTANT QUESTIONS

27
1. Explain the complete lifecycle of a Java Applet with a diagram. What is the
significance of each lifecycle method?

2. Differentiate between Applet and Application in Java. Why do applets not


have a main() method? Explain with examples.

3. What is the Event Delegation Model in Java? Explain with a detailed


example showing event source, event object, and event listener.

4. Compare and contrast AWT and Swing. List at least five differences and
explain when you would choose one over the other.

5. Explain the purpose and usage of Adapter classes in Java event handling.
Why are adapter classes not available for ActionListener and ItemListener?

6. Describe all five Layout Managers in Java AWT with examples. Which
layout manager would you use for creating a calculator interface and why?

7. How do you pass parameters from an HTML page to a Java Applet? Write
a complete example showing parameter passing and retrieval.

8. Explain the Graphics class in Java with at least 10 different drawing


methods. Write a program to draw a house using various shapes.

9. What are the differences between JApplet and Applet? Why is


getContentPane() used in JApplet? Explain with code examples.

10. Discuss the component hierarchy in AWT and Swing. Explain the role of
Component, Container, and JComponent classes with their relationships.

28

You might also like