tag in HTML, and discusses the event-driven nature of applets, emphasizing user interaction and the importance of repainting. Additionally, it outlines the class hierarchy in AWT, including components like Frame and Canvas, and the differences between AWT and Swing applets."> tag in HTML, and discusses the event-driven nature of applets, emphasizing user interaction and the importance of repainting. Additionally, it outlines the class hierarchy in AWT, including components like Frame and Canvas, and the differences between AWT and Swing applets.">
[go: up one dir, main page]

0% found this document useful (0 votes)
21 views18 pages

Unit Iv Awt

The document provides an overview of AWT controls, applet classes, and event handling in Java, detailing components like labels, buttons, and panels, as well as the applet lifecycle methods such as init(), start(), and paint(). It explains the structure of applets, including the use of the <APPLET> tag in HTML, and discusses the event-driven nature of applets, emphasizing user interaction and the importance of repainting. Additionally, it outlines the class hierarchy in AWT, including components like Frame and Canvas, and the differences between AWT and Swing applets.

Uploaded by

PRIYA
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)
21 views18 pages

Unit Iv Awt

The document provides an overview of AWT controls, applet classes, and event handling in Java, detailing components like labels, buttons, and panels, as well as the applet lifecycle methods such as init(), start(), and paint(). It explains the structure of applets, including the use of the <APPLET> tag in HTML, and discusses the event-driven nature of applets, emphasizing user interaction and the importance of repainting. Additionally, it outlines the class hierarchy in AWT, including components like Frame and Canvas, and the differences between AWT and Swing applets.

Uploaded by

PRIYA
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
You are on page 1/ 18

UNIT IV AWT Controls: The AWT class hierarchy-user interface components – Labels -

Button-Text Components - Check Box - Check Box Group - Choice -List Box - Panels
– Scroll Pane - Menu - Scroll Bar. Working with Frame class - Colour - Fonts and
layout managers.
Event Handling: Events-Event sources-Event Listeners - Event Delegation Model
(EDM) – Handling Mouse and Keyboard Events - Adapter classes – Inner classes

Herbert Schildt, The Java Complete Reference, Tata Mc Graw Hill, New Delhi, 7th Edition, 2010

Overview of Applet Class in Java


The Applet class, found in the java.applet package, forms the foundation of Java applets. Applets are
small Java programs that run inside a web browser or applet viewer, providing interactive content on web
pages. They are window-based and event-driven, unlike traditional console applications.

Two Types of Applets


1. AWT-based Applets:
o Use Abstract Window Toolkit (AWT) for GUI.
o Traditional, available since Java was first introduced.
o Suitable for simple user interfaces.
2. Swing-based Applets (JApplet):
o Use Swing classes for richer, modern GUI.
o Subclass JApplet, which itself inherits Applet.
o More commonly used now.
o Some additional constraints compared to AWT-based applets.

Basic Structure of an Applet


 Applets do not start with main() like console applications.
 They are embedded in HTML using the APPLET tag (deprecated in modern browsers but still
foundational in Java learning).
 Run using applet viewers like appletviewer.
Example of APPLET Tag (as a comment in Java file):
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/

Key Lifecycle Methods in Applet


Method Purpose Called when
init() Initialize variables, setup UI First time when applet is loaded
start() Start/resume execution After init() and when applet is revisited
paint(Graphics g) Draw output, handle graphics Whenever applet needs to refresh/redraw
Suspend execution (pause
stop() When browser leaves the page or minimizes applet
activities like threads)
destroy() Cleanup resources Before applet is removed from memory

Applet Skeleton
1
Applet Initialization and Termination
It is important to understand the order in which the various methods shown in the skeleton
are called. When an applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )

init( )
The init( ) method is the first method to be called. This is where you should initialize variables. This
method is called only once during the run time of your applet.
start( )
The start( ) method is called after init( ). It is also called to restart an applet after it has been
stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is called
each time an applet’s HTML document is displayed onscreen.
paint( )
The paint( ) method is called each time your applet’s output must be redrawn. This situation
can occur for several reasons. The paint( ) method has one parameter of type Graphics. This parameter
will contain the graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required.
stop( )
The stop( ) method is called when a web browser leaves the HTML document containing the
applet—when it goes to another page.
destroy( )
The destroy( ) method is called when the environment determines that your applet needs to
be removed completely from memory.
Overriding update( )
This method is called when your applet has requested that a portion of its window be redrawn. The default
version of update( ) simply calls paint( ).

import java.awt.*;
import java.applet.*;
/* <applet code="AppletSkel" width=300 height=100>
</applet> */
public class AppletSkel extends Applet {
public void init() {
// Initialization code
}
public void start() {
// Start or resume execution
}

public void stop() {


// Suspend execution

2
}

public void destroy() {


// Cleanup before applet is destroyed
}

public void paint(Graphics g) {


// Redraw contents (like drawString)
}
}

Methods in Applet Class


Method Description
void init() Initialization work.
void start() Starts/resumes execution.
void stop() Suspends execution.
void destroy() Cleanup resources.
void paint(Graphics g) Handles applet graphics and output.
void showStatus(String msg) Displays message in browser's status window.
URL getDocumentBase() Gets URL of the HTML file containing the applet.
URL getCodeBase() Gets URL of applet code location.
AudioClip getAudioClip(URL u) Loads an audio clip.
Image getImage(URL u) Loads an image.
String getParameter(String param) Retrieves parameter value from HTML APPLET tag.

Basic Applet Life Cycle Sequence


On start:
init() -> start() -> paint()
On end (or leaving page):
stop() -> destroy()

Drawing on Applet (Simple Display Method)


update( ) or paint( ).
It has the following general form:
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x,y.
 Use drawString() to output text:
public void paint(Graphics g) {
g.drawString("Hello Applet!", 20, 20);
}
 Coordinates (x, y) define where the string starts. (0,0) is the top-left corner.
To set the background color of an applet’s window, use setBackground( ). To set the
foreground color use setForeground( ).These methods are defined by Component, and they have the
following general forms:
void setBackground(Color newColor)

3
void setForeground(Color newColor)
Here, newColor specifies the new color. The class Color defines the constants shown here
that can be used to specify colors:
Color.black ,Color.magenta,Color.blue, Color.orange,Color.cyan ,Color.pink,Color.darkGray ,
Color.red, Color.gray, Color.white,Color.green ,Color.yellow,Color.lightGray
setBackground(Color.green);
setForeground(Color.red);
Agood place to set the foreground and background colors is in the init( ) method.
getBackground( ) and getForeground( ), respectively. They are also defined by Component
and are shown here:
Color getBackground( )
Color getForeground( )
Here is a very simple applet that sets the background color to cyan, the foreground color
to red, and displays a message that illustrates the order in which the init( ), start( ), and paint( )
methods are called when an applet starts up:

Event-Driven Nature of Applets


 Applets respond to events like mouse clicks, key presses.
 No continuous loop; applet waits for user interaction.
 If repetitive action needed (like animation), threads are used.

Applet Architecture
1. Event-Driven Nature:
 Applets are event-driven programs, meaning they respond to events like mouse clicks, key
presses, etc.
 They do not run continuously or sequentially like console-based programs.
 When an event happens, Java's runtime system calls a specific method (event handler) in the
applet to handle it.
 After responding to the event, control is returned immediately to the system — no long-running
operations in the main thread.
 If a task needs to run continuously (like animation), a separate thread must be used.

2. User-Initiated Interaction:
 In console programs, the program asks for input and waits (e.g., readLine()).
 In applets, the user interacts freely (e.g., clicking a button, moving a mouse).
 These user actions generate events, and the applet responds.
 Example events:
o Mouse click → mouseClicked event
o Key press → keyPressed event
o Button press → actionPerformed event

3. Applet as a Window-Based Program:


 Applets run inside a web browser or applet viewer.
 They display a window/interface and handle user interactions.
 Similar to Windows programming, but simpler due to Java's clean and well-organized API.

4
Requesting Repainting in Applets
1. Window Updates via paint( ) and update( ):
o Applets draw on their window when AWT (Abstract Window Toolkit) calls paint() or
update().
o Direct drawing inside loops is NOT allowed inside paint() because applets must return
control quickly to the runtime system.

 To refresh/redraw the applet window when new information is ready, call repaint().
 repaint() requests AWT to call update(), which then calls paint().
 Inside paint(), the applet uses updated data (like text or images) and displays it.

Forms of repaint( ):

Form Usage
void repaint() Repaint the entire applet window.
void repaint(int x, int y, int width, Repaint only a specific rectangular region — more
int height) efficient when only part of window changes.
void repaint(long maxDelay)
Repaint entire window, but specify max delay
(milliseconds) before repainting happens.
void repaint(long maxDelay, int x, int
y, int width, int height) Repaint a specific region, with max delay.

HTML <APPLET> Tag — Structure and Explanation


The <APPLET> tag is used in an HTML file to embed and run a Java Applet in a webpage or an applet
viewer.

General Syntax:
<APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
[<PARAM NAME = AttributeName VALUE = AttributeValue>]
...
[HTML displayed if Java is not supported]
</APPLET>

Explanation of Attributes:

Attribute Required? Purpose


CODEBASE Optional URL path to locate the applet's .class file. Defaults to current
5
Attribute Required? Purpose
directory if omitted.
CODE Required Name of the applet's compiled .class file.
ALT Optional Message shown if the browser recognizes <APPLET> but can't run it.
Gives a name to the applet instance — used for communication
NAME Optional
between applets on the same page.
WIDTH & HEIGHT Required Set the size (in pixels) of the applet display area.
Aligns applet like an image — options: LEFT, RIGHT, TOP,
ALIGN Optional
BOTTOM, MIDDLE, etc.
VSPACE & HSPACE Optional Vertical and horizontal space around the applet (in pixels).
PARAM NAME/
Optional Passes parameters to the applet — accessed using getParameter().
VALUE
ARCHIVE Optional Specifies JAR (Java archive) files containing applet classes/resources.
OBJECT Optional Specifies a serialized applet object file (advanced usage).

Modern browsers no longer support Java Applets due to security issues. Applets are primarily used in
legacy systems or viewed with applet viewers (like the appletviewer tool in JDK).

Passing Parameters to Applet


Use <PARAM> tags inside <APPLET> to pass custom data to the applet.

How to Access Parameters:

 Inside your applet code, use getParameter("paramName") to retrieve the value as a String.

Explanation of Code:

Part Description
getParameter("paramName") Retrieves value passed via <param> as String.
Integer.parseInt(param) Converts String to int.
Float.parseFloat(param) Converts String to float.
Boolean.parseBoolean(param) Converts String to boolean.
paint(Graphics g) Displays retrieved parameter values.

6
Window Fundamentals in AWT
The AWT (Abstract Window Toolkit) in Java provides a set of classes for creating graphical user
interfaces (GUI) and handling window-based applications.

Class Hierarchy Overview:


Here’s a simple way to understand how the different classes are related:

Component
└── Container
├── Panel
│ └── Applet (used for web-based applications)
└── Window
└── Frame (normal application window)

 Component is the base for


everything.
 Container can hold
components. Use methods like
add() to place components
inside
 Panel is a simple container
(like Applet). For embedding
UI elements inside other
containers.
 Window/Frame are top-level
windows for applications.
 Canvas For custom drawings/graphics.

Component (Superclass for all GUI elements):

 Abstract class — You can't create an object of this directly.


 All visual elements (buttons, text fields, windows) extend Component.
 Manages basic attributes like size, location, color, font, and event handling (mouse, keyboard).
 Example methods:
o setSize(), setLocation(), repaint(), addMouseListener(), etc.

Container (Subclass of Component):

 Can hold other Components (like buttons, text fields, panels).


 Supports nesting — a container can hold other containers (multi-level UI).
 Responsible for layout management (organizing components on screen).
 Example methods:
o add(Component c): Adds a component.
o setLayout(LayoutManager lm): Sets layout for arranging components.

7
Panel (Subclass of Container):

 A simple container to hold components.


 No title bar, border, or menu.
 Superclass of Applet, so when you write an Applet, you are actually working with a Panel.
 Often used for grouping components.
 You add components to it and arrange them using layout managers.
 Example:
 Panel p = new Panel();
 p.add(new Button("Click Me"));

Window (Subclass of Container):

 Represents a top-level window (not contained inside any other container).


 Doesn't have title bar or menu bar, but serves as a base for other windows.
 Usually not used directly — we use its subclass Frame instead.

Frame (Subclass of Window):

 Standard application window.


 Has title bar, borders, menu bar, and resize controls.
 Can be created in standalone applications or applets.
 Example:
 Frame f = new Frame("My First Frame");
 f.setSize(300, 200);
 f.setVisible(true);
 Security Note: If created inside an Applet, the Frame shows a warning label ("Java Applet
Window") for user safety.

Canvas (Special Component for Drawing):

 Not part of Panel/Frame hierarchy but useful.


 Represents a blank rectangular area for custom graphics/drawing.
 You can draw shapes, images, text using paint(Graphics g) method.
 Example:
 class MyCanvas extends Canvas {
 public void paint(Graphics g) {
 g.drawString("Hello, Canvas!", 50, 50);
 }
 }

Frame Full-fledged application window with title bar, etc.


Canvas Blank area for drawing graphics.

4. Visualizing the Class Hierarchy:


8
Component (abstract)
└── Container
├── Panel
│ └── Applet
└── Window
└── Frame
Canvas (direct subclass of Component)

5. Practical Example — Creating a Frame Window:


import java.awt.*;

public class SimpleFrame {


public static void main(String[] args) {
Frame f = new Frame("My First Window"); // Create Frame with title
f.setSize(400, 300); // Set size
f.setVisible(true); // Make visible
}
}

9
10
11
A Frame in Java is a top-level window with a title, border, menu bar, and buttons for minimizing,
maximizing, and closing the window. It is part of the Abstract Window Toolkit (AWT) and Swing libraries
and is commonly used to create Graphical User Interface (GUI) applications.
1. Frame in AWT (java.awt.Frame)
In AWT, the Frame class is a subclass of Window, which means it is an independent, resizable window.
Window in Swing (JFrame)
In Swing, a window is typically created using the JFrame class, which is a top-level container that can hold
other components like buttons, text fields, and panels.

Dialog Window in Swing (JDialog)


A dialog window is a small pop-up window that appears over a parent window to display messages, take
input, or show warnings. In Swing, dialog windows are created using the JDialog or JOptionPane classes.
1. Creating a Simple Dialog using JDialog
JDialog is a top-level container like JFrame, but it is primarily used for pop-up windows.
2. Using JOptionPane for Simple Dialogs
Swing provides JOptionPane to create standard dialogs easily.
(a) Message Dialog
Displays a simple information message.
(b) Confirmation Dialog
Asks the user to confirm an action (Yes/No/Cancel).
int choice = JOptionPane.showConfirmDialog(null, "Do you want to continue?", "Confirm",
JOptionPane.YES_NO_CANCEL_OPTION);

if (choice == JOptionPane.YES_OPTION) {
System.out.println("User selected YES");
} else if (choice == JOptionPane.NO_OPTION) {
System.out.println("User selected NO");
} else {
System.out.println("User selected CANCEL")
(c) Input Dialog
Makes user input through a pop-up.
String name = JOptionPane.showInputDialog(null, "Enter your name:", "Input",
JOptionPane.QUESTION_MESSAGE);

if (name != null && !name.isEmpty()) {


12
System.out.println("User entered: " + name);
} else {
System.out.println("User canceled input");

(d) Option Dialog (Custom Buttons)


Allows creating custom button options.
import javax.swing.*;

public class OptionDialog {


public static void main(String[] args) {
String[] options = {"Red", "Blue", "Green"};

int choice = JOptionPane.showOptionDialog(


null,
"Choose a color:",
"Color Selection",
JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]
);

if (choice >= 0) {
System.out.println("User chose: " + options[choice]);
} else {
System.out.println("User closed the dialog");
}
}
}

13
Dialog Type Method Description

Message Dialog showMessageDialog() Displays an info message.

Confirmation Dialog showConfirmDialog() Asks Yes/No/Cancel.

Input Dialog showInputDialog() Takes user input.

Custom Option Dialog showOptionDialog() Custom buttons/options.

Layout Managers in Java Swing


Layout managers in Swing are used to arrange components within a container (like JPanel, JFrame). Java
provides several built-in layout managers, each with different ways of organizing components.

1. FlowLayout (Default for JPanel)


 Arranges components from left to right.
 If space is insufficient, components move to the next row.
 Default alignment is center.
Example:
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT)); // Aligns left
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));

2. BorderLayout (Default for JFrame)


 Divides the container into five regions:
NORTH, SOUTH, EAST, WEST, CENTER.
 The center area expands to take available space.
Example:
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("Center"), BorderLayout.CENTER);

3. GridLayout
14
 Divides the container into equal-sized rows and columns.
 All components get the same size.
Example (2 rows, 3 columns):
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 3));
for (int i = 1; i <= 6; i++) {
panel.add(new JButton("Button " + i));
}

4. BoxLayout
 Arranges components vertically or horizontally.
 Provides flexible spacing.
Example (Vertical alignment):
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));

5. CardLayout
 Stacks components like a deck of cards.
 Only one component is visible at a time.
Example:
CardLayout cardLayout = new CardLayout();
JPanel panel = new JPanel(cardLayout);

panel.add(new JButton("Card 1"), "Card1");


panel.add(new JButton("Card 2"), "Card2");

cardLayout.show(panel, "Card2"); // Show "Card2"

6. GridBagLayout (Most Flexible)


 Advanced layout manager with precise control over component positioning.
 Allows setting weights, constraints, and spacing.
15
Example:
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(new JButton("Button 1"), gbc);

Choosing the Right Layout Manager


Layout Manager Best For

FlowLayout Simple layouts, small components

BorderLayout Main windows with multiple regions

GridLayout Uniform button panels, forms

BoxLayout Flexible vertical or horizontal alignment

CardLayout Tabbed interfaces, multiple views

GridBagLayout Complex UI, custom spacing

16
Adapter Classes
Adapter classes are abstract classes that provide empty implementations of event listener interfaces.
They allow you to override only the methods you need, instead of implementing all methods from an
interface.
use
 Many listener interfaces (e.g., MouseListener, WindowListener) contain multiple methods, even if
you only need one.
 Implementing all methods can be unnecessary and cluttered.
 Adapter classes solve this by providing default (empty) implementations.
 You extend an adapter class and override only the methods you need.

Common Adapter Classes

Corresponding
Adapter Class Methods Available
Listener

mouseClicked(), mouseEntered(), mouseExited(), mousePressed(),


MouseAdapter MouseListener
mouseReleased()

KeyAdapter KeyListener keyPressed(), keyReleased(), keyTyped()

windowOpened(), windowClosing(), windowClosed(),


WindowAdapter WindowListener windowIconified(), windowDeiconified(), windowActivated(),
windowDeactivated()

FocusAdapter FocusListener focusGained(), focusLost()

Difference Between Adapter Class and Listener Interface

Feature Adapter Class Listener Interface

Implements Empty methods All methods must be implemented

Usage Subclass and override only needed methods Implement all methods, even if unused

Readability Cleaner, easier to maintain More boilerplate code

Example MouseAdapter, KeyAdapter MouseListener, KeyListener

17
Inner Classes in Java
An inner class in Java is a class that is declared inside another class. It helps group logically related
classes together and provides better encapsulation.

Types of Inner Classes


Java has four types of inner classes:

Type Description

1. Member Inner Class A class defined inside another class, but outside any method.

2. Local Inner Class A class defined inside a method and used only within that method.

3. Anonymous Inner Class A class without a name, declared and instantiated at the same time.

4. Static Nested Class A static inner class that does not require an instance of the outer class.

18

You might also like