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.">
Unit Iv Awt
Unit Iv Awt
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
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
}
2
}
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:
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
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.
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:
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).
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.
Component
└── Container
├── Panel
│ └── Applet (used for web-based applications)
└── Window
└── Frame (normal application window)
7
Panel (Subclass of Container):
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.
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 (choice >= 0) {
System.out.println("User chose: " + options[choice]);
} else {
System.out.println("User closed the dialog");
}
}
}
13
Dialog Type Method Description
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);
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.
Corresponding
Adapter Class Methods Available
Listener
Usage Subclass and override only needed methods Implement all methods, even if unused
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.
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