Unit - 4 Java
Unit - 4 Java
SCCPC21
UNIT - 4
Overview Of Unit - 4
AWT Controls Event Handling
AWT Class Hierarchy Events
User Interface Components Event Sources
Labels Event Listeners
Button Event Delegation Model (EDM)
Text components Handling Mouse and Keyboard Events
Check Box Adapter Classes
Check Box Group Inner Classes.
Choice
List Box
Panels
Scroll Pane
Menu , Scroll Bar
Working with Grame Class
Color
Fonts And Layout Managers.
1⃣ AWT Class Hierarchy AWT Controls
Introduction to AWT
AWT stands for Abstract Window Toolkit.
It is a part of Java used for creating Graphical User Interface (GUI) applications.
AWT classes are available in the [Link] package.
It provides components like Button, Label, TextField, Frame, etc.
AWT is platform dependent because it uses native operating system components (called peer
components).The structure of AWT is organized using inheritance, forming.
AWT is one of the earliest GUI toolkits provided by Java.
import [Link].*;
🔹 What is GUI?
GUI stands for Graphical User Interface.
It allows users to interact with a program using:
Windows, Buttons, Text boxes, Menus, Checkboxes, Scroll bars
Instead of typing commands, users can click and interact visually.
Example:
Calculator window, Login form, Registration form, ATM interface
AWT Controls Object
🔹 Explanation |
User Interface (UI) Components are the visual elements that allow users to interact with a program.
In AWT (Abstract Window Toolkit), these components are provided through the [Link] package. They help in:
Displaying information
Accepting user input
Performing actions
Organizing the interface.
AWT Controls
These components are also called controls or widgets.
AWT UI components are classified into:
AWT provides many UI components: Choice
Label List
Button Scrollbar
TextField Menu
TextArea Panel
Checkbox Frame
These components help in interacting with the user.
Now let us explain each component in detail.
🔷 1⃣ Label
📌 Definition:
A Label is used to display non-editable text to the user.
📌 Purpose:
To show messages
To display field names (like Name, Age)
To provide instructions
AWT Controls
📌 Characteristics:
✔ Cannot be edited
✔ Used only for displaying information
✔ Lightweight display control
Label l=new Label(“Hello Students”);
📌 Example Usage:
Used in forms like:
Name: [________]
Here “Name:” is a Label.
🔷 2⃣ Button AWT Controls
📌 Definition:
A Button is used to trigger an action when clicked.
📌 Purpose:
Submit form
Reset form
Perform calculations
Close window
📌 Characteristics:
✔ Generates ActionEvent
✔ Used with event handling
✔ Interactive component
📌 Real-world Example:
Login button in a website.
When user clicks → Some action is performed.
AWT Controls
🔷 3⃣Text Components
There are two types:
(a) Text Field
TextField is used to accept single-line input from the user. TextField t = new TextField(20);
📌 Uses:
✔ Username input
✔ Password input
✔ Short data entry
(b) Text Area
TextArea is used to accept multi-line input.(Scrollable) TextArea ta = new TextArea(5, 30);
📌 Uses:
✔ Comments
✔ Address
✔ Description
AWT Controls
Text Area
Text Field
AWT Controls
🔷 4⃣Checkbox
📌 Definition:
Checkbox allows the user to select one or more options.
Checkbox c1 = new Checkbox("Java");
📌 Uses:
✔ Selecting hobbies
✔ Choosing skills
✔ Multiple selection allowed
Example:
☑ Java
☑ Python
☑ C++
User can select multiple options.
AWT Controls
🔷 5⃣Checkbox Group
📌 Definition:
Checkbox Group
Used for radio buttons (only one option selected).
📌 Features:
✔ Shows only one option at a time
✔ Saves space
✔ Allows single selection
📌 Used in:
Selecting country
Selecting course
Selecting gender
User selects only one item.
🔷 7⃣ List Box AWT Controls
📌 Definition:
List displays multiple items in a list format.
📌 Features:
✔ Inherits from Container
✔ Default layout is Flow Layout
✔ Used to divide window into sections
Example:
One panel for login details
One panel for buttons
🔷 9⃣ Scroll bar AWT Controls
📌 Definition:
Scrollbar is used to scroll content horizontally or vertically.
📌 Types:
Horizontal Scrollbar
Vertical Scrollbar
📌 Used in:
Text editors
Long content windows
Adjustable value selection
AWT Controls
🔷 🔟 Scroll Pane
📌 Definition:
ScrollPane provides scrolling facility.
📌 🔹 Important Methods
setSize(width, height)
setVisible(true)
setLayout()
add(Component)
AWT Controls
🔷 1⃣3⃣ Color in AWT
📌 Definition:
Color class is used to set background and foreground colors.
setBackground([Link]);
setForeground([Link]);
📌 🔹 Predefined Colors
[Link]
[Link]
[Link]
[Link]
[Link]
AWT Controls
🔷 1⃣4⃣ Fonts in AWT
📌 Definition:
Font class is used to change text style.
📌 🔹 Font Styles
[Link]
[Link]
[Link]
AWT Controls
🔷 1⃣4⃣ Layout Managers
📌 Definition:
Layout managers control how components are arranged.
setLayout(new GridLayout(2,2));
🔹 Types of Layout Managers
1. Flow Layout
Default layout of Panel
Arranges left to right
2. BorderLayout : Default layout of Frame
5 regions:
NORTH
SOUTH
EAST
WEST
CENTER
3. GridLayout : Arranges in rows and columns
4. CardLayout : Multiple components in same space
AWT Controls
🌟 Advantages of AWT
✔ Simple to use
✔ Built-in components
✔ Event handling support
🌟 Disadvantages
❌ Platform dependent
❌ Less powerful than Swing
🔚 Conclusion
AWT is the foundation for building GUI applications in Java. It provides:
Controls (Button, Label, TextField)
Containers (Panel, Frame)
Layout Managers
Color and Font customization
Understanding AWT helps students learn advanced GUI frameworks like Swing and JavaFX.
Event Handling
🔷 1⃣ Introduction to Event Handling
In GUI programming, the program does not run in a straight sequence like console programs.
Instead, it waits for the user to perform some action.
When a user:
Clicks a button
Presses a key
Moves the mouse
Closes a window
An event is generated.
Handling these events is called Event Handling.
Java AWT follows the Event Delegation Model (EDM) for handling events.
🔷 2⃣ Events
📌 Definition:
An Event is an object that describes a change in the state of a source.
In simple words:
👉 An event is something that happens because of user interaction.
Event Handling
🔷 Events
The events are defined as an object that describes a change in the state of a source object. Java defines a
number of such Event Classes inside import [Link].*; package.
Action Event : Occurs when a button is clicked or an action is performed.
Mouse Event : Triggered by mouse actions (click, drag, move).
Key Event : Generated when a key is pressed, released, or typed.
Focus Event : Occurs when a component gains or loses focus.
Item Event : Fired when an item is selected/deselected (e.g., checkbox).
🔷 3⃣ Event Source
A source is an object that generates an event. An event generation occurs when an internal state of that
object changes in some way. A source must register listeners in order for the listeners to receive notifications
about a specific type of event.
Some of the event sources are as follows:
Button: Generates an ActionEvent when clicked.
CheckBox: Generates an ItemEvent on selection change.
List: Fire ActionEvent or ItemEvent on item selection.
Choice: Triggers ItemEvent when an option is chosen.
Window: Shows WindowEvent on close/minimize/maximize.
[Link](this);
Here:
b → Event source
this → Listener
Example :
import [Link].*;
import [Link].*;
import [Link].*;
public class EventListenerTest extends JFrame implements ActionListener {
JButton button; public void actionPerformed(ActionEvent ae) {
public static void main(String args[]) { if([Link]() == button) {
EventListenerTest object = new EventListenerTest(); [Link](null, "Generates an
[Link](); Action Event");
} }
void createGUI() { }
button = new JButton(" Click Me !"); }
setSize(300,200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
add(button);
[Link](this);
}
🔷 5⃣ Event Delegation Model (EDM) :
The Event Delegation Model (EDM) is a design pattern used to manage event handling by separating the event
source (the component generating the event) from the listener (the object processing it). In Java, this
decoupling improves modularity and maintainability. In web development, "event delegation" specifically refers
to attaching a single event listener to a common ancestor to manage events for multiple child elements
efficiently by leveraging event bubbling.
Source: Events are generated from the source. There are various sources like buttons, checkboxes, list,
menu-item, choice, scrollbar, text components, windows, etc., to generate events.
Listeners: Listeners are used for handling the events generated from the source. Each of these listeners
represents interfaces that are responsible for handling events.
Event Delegation Model (EDM) :
📌 Working Steps:
1⃣ Event occurs
2⃣ Event object is created
3⃣ Event source sends event to registered listener
4⃣ Listener handles event
📌 Advantages of EDM:
✔ Efficient
📌 Example Flow: ✔ Flexible
Button clicked
✔ Multiple listeners possible
↓ ✔ Clean separation of source and handler
ActionEvent created
↓
ActionListener receives event
↓
actionPerformed() method executes
🔷 1⃣ Handling Mouse Events
📌 What are Mouse Events?
Mouse events are generated when the user interacts with a component using the mouse.
Examples of mouse actions:
Clicking the mouse
Pressing a mouse button
Releasing a mouse button
Moving the mouse
Entering or exiting a component area
All mouse-related events are handled using classes and interfaces from : import [Link].*;
📌 MouseListener Interface
To handle mouse events, we use the MouseListener interface.
Methods of MouseListener : If a class implements MouseListener, it must override all five methods.
mouseClicked(MouseEvent e)
mousePressed(MouseEvent e)
mouseReleased(MouseEvent e)
mouseEntered(MouseEvent e)
mouseExited(MouseEvent e)
🔷 Example Program :
import [Link].*;
import [Link].*;
class MouseExample extends Frame implements MouseListener {
MouseExample() {
addMouseListener(this);
setSize(300,200);
Explanation:
setVisible(true);
addMouseListener(this) registers the listener.
}
When mouse is clicked → mouseClicked() method executes.
public void mouseClicked(MouseEvent e) {
📌 MouseMotionListener
[Link]("Mouse Clicked");
To detect mouse movement:
}
Methods:
public void mousePressed(MouseEvent e) {}
mouseMoved(MouseEvent e)
public void mouseReleased(MouseEvent e) {}
mouseDragged(MouseEvent e)
public void mouseEntered(MouseEvent e) {}
Used in drawing applications and games.
public void mouseExited(MouseEvent e) {}
public static void main(String args[]) {
new MouseExample();
}
}
Example :
🔷 2⃣ Handling Keyboard Events package test;
📌 What are Keyboard Events? import [Link].*;
Keyboard events are generated when the user presses or
import [Link].*;
releases a key.
class KeyExample extends Frame implements KeyListener {
These are handled using KeyListener interface. KeyExample() {
📌 KeyListener Methods: addKeyListener(this);
setSize(300,200);
keyPressed(KeyEvent e) setVisible(true);
keyReleased(KeyEvent e) }
keyTyped(KeyEvent e) public void keyPressed(KeyEvent e) {
[Link]("Key Pressed");
keyPressed()→ When key is pressed }
keyReleased() → When key is released public void keyReleased(KeyEvent e) {}
keyTyped() → When character is typed public void keyTyped(KeyEvent e) {}
public static void main(String args[]) {
new KeyExample();
}
}
🔷 3⃣ Adapter Classes Example :
Even if we need only one method, we must override all. [Link]("Mouse Clicked");
KeyAdapter } Advantages:
WindowAdapter } ✔ No need to override all methods
FocusAdapter ✔ Code becomes shorter
✔ Improves readability
import [Link].*;
🔷 4⃣ Inner Classes import [Link].*;
📌 What is an Inner Class? class InnerExample extends Frame {
An inner class is a class defined inside another class.
Button b;
InnerExample() {
Syntax:
b = new Button("Click");
class Outer {
add(b);
class Inner {
setSize(300,200);
}
[Link](new MyListener());
}
setVisible(true);
}
📌 Why Inner Classes are Used in Event Handling? class MyListener implements ActionListener {
✔ Organizes event-handling code public void actionPerformed(ActionEvent e) {
✔ Improves readability [Link]("Button Clicked");
✔ Can access outer class variables }
✔ Avoids separate class files }
Explanation:
public static void main(String args[]) {
MyListener is inner class.
new InnerExample();
It handles button click event.
}
It can access outer class variables easily.
}
🔷 5⃣ Anonymous Inner Class
We can also write inner classes without giving name.
Example:
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked");
}
});