UNIT-5
Event Driven Programming: -
Event-Driven Programming in Java is a programming paradigm where the flow of the
program is determined by events such as user interactions (mouse clicks, key presses),
sensor outputs, or messages from other programs.
Java supports event-driven programming extensively through its Abstract Window Toolkit
(AWT) and Swing libraries. Events are handled via event listeners and event sources.
Key Concepts
1. Event Source
• The component that generates an event.
• Example: JButton, JTextField, JFrame, etc.
2. Event Object
• Contains information about the event.
• Example: ActionEvent, MouseEvent, KeyEvent, etc.
3. Event Listener
• An interface that contains methods to respond to an event.
• You register a listener to an event source.
4. Event Handling
• The process of responding to events.
Types of Event Listeners in Java:
1. ActionListener – For button clicks, menu selections.
2. MouseListener / MouseMotionListener – For mouse click, enter, exit, drag, move.
3. KeyListener – For key press, release, and type events.
4. WindowListener – For window open, close, minimize, etc.
5. ItemListener – For checkbox, combo box item changes.
6. FocusListener – For focus gained/lost.
7. ChangeListener – For sliders, progress bars, etc.
Graphics programming: -
Graphics programming in Java allows you to draw shapes, text, images, and perform
animations. It is mainly done using AWT (Abstract Window Toolkit) and Swing libraries,
especially via the Graphics and Graphics2D classes.
Key Classes for Graphics:
1. java.awt.Graphics – Basic drawing methods (lines, ovals, rectangles, etc.)
2. java.awt.Graphics2D – Advanced features like transformations, stroke control, etc.
3. javax.swing.JPanel – Used as a canvas by overriding paintComponent(Graphics g)
Frame: -
In Java, a Frame is a top-level window with a title and a border used to create GUI
applications. It's part of the AWT (Abstract Window Toolkit) package.
Basics of event handling: -
An event is a change in the state of an object triggered by some action such as Clicking a
button, Moving the cursor, Pressing a key on the keyboard, Scrolling a page, etc. In Java,
the java.awt.event package provides various event classes to handle these actions.
Classification of Events: -
Events in Java can be broadly classified into two categories based on how they are
generated:
1. Foreground Events: Foreground events are the events that require user interaction
to generate. Examples of these events include Button clicks, Scrolling the scrollbar,
Moving the cursor, etc.
2. Background Events: Events that don't require interactions of users to generate are
known as background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.
Event Handling in Java is the mechanism that deals with user interactions like:
• Clicking a button
• Typing in a text field
• Moving the mouse
• Closing a window
When such an action happens, an event is generated, and Java provides a way to listen to
these events and respond to them using event listeners.
Event Handling Model
Java uses the delegation event model which includes:
Role Description
Event Source Component that generates an event (e.g., JButton)
Event Object Holds information about the event (ActionEvent, MouseEvent)
Event Interface with methods to handle the event (ActionListener,
Listener MouseListener)
Event handlers: -
An Event Handler in Java is the code (a method) that runs when an event occurs (like a
button is clicked, key is pressed, etc.).
Event handlers are defined in listener interfaces and are triggered by the event source.
Adapter classes: -
An Adapter Class is a default (empty) implementation of a listener interface that contains
multiple methods.
➤ Purpose:
They allow you to override only the method(s) you need, rather than all the methods in the
interface.
Common Adapter Classes in AWT/Swing
Interface Adapter Class Use Case
MouseListener MouseAdapter Mouse click, press, release, etc.
MouseMotionListener MouseMotionAdapter Mouse drag or move
KeyListener KeyAdapter Key press/release/typed
WindowListener WindowAdapter Window open, close, minimize, etc.
FocusListener FocusAdapter Focus gained/lost
Actions: -
In Swing, an Action is a more powerful alternative to ActionListener.
It allows you to:
• Handle events (like button clicks or menu item selections)
• Share behavior (same logic for multiple buttons or keys)
• Manage name, icon, keyboard shortcuts, tooltips, and more — all in one place.
Difference Between ActionListener and Action
Feature ActionListener Action
Basic click handling Yes Yes
Supports button name, icon, tooltip No Yes
Can be reused by multiple components No Yes
Mouse events: -
Mouse events in Java are actions triggered by the user's mouse, such as:
Event Description
Mouse Click When mouse is clicked
Mouse Press When mouse button is pressed
Mouse Release When mouse button is released
Mouse Enter When mouse enters a component
Mouse Exit When mouse exits a component
Mouse Move / Drag When mouse is moved or dragged
MouseListener and MouseMotionListener is an interface in java.awt.event package . Mouse
events
are of two types. MouseListener handles the events when the mouse is not in motion. While
MouseMotionListener
handles the events when mouse is in motion.
There are five types of events that MouseListener can generate. There are five abstract
functions that represent these five events.
The abstract functions are :
1. void mouseReleased(MouseEvent e) : Mouse key is released
2. void mouseClicked(MouseEvent e) : Mouse key is pressed/released
3. void mouseExited(MouseEvent e) : Mouse exited the component
4. void mouseEntered(MouseEvent e) : Mouse entered the component
5. void mousepressed(MouseEvent e) : Mouse key is pressed
JAVA AWT: -
Java AWT or Abstract Window Toolkit is an API used for developing GUI(Graphic User
Interfaces) or Window-Based Applications in Java. Java AWT is part of the Java Foundation
Classes (JFC) that provides a way to build platform-independent graphical applications.
Java AWT Hierarchy: -
• Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
• Containers: AWT provides containers like panels, frames, and dialogues to organize
and group components in the Application.
• Layout Managers: Layout Managers are responsible for arranging data in the
containers some of the layout managers are BorderLayout, FlowLayout, etc.
• Event Handling: AWT allows the user to handle the events like mouse clicks, key
presses, etc. using event listeners and adapters.
• Graphics and Drawing: It is the feature of AWT that helps to draw shapes, insert
images and write text in the components of a Java Application.
Introduction to Swing: layout management: -
Layout Managers control the position and size of components inside a container (like a
JPanel or JFrame).
Why Use Layouts?
• Resizable GUIs
• Platform-independent positioning
• Avoids hardcoding setBounds()
AWT Layout Manager Classes
Following is the list of commonly used controls while designing GUI using AWT.
Sr.No. LayoutManager & Description
1 BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south, and
center.
2 CardLayout
The CardLayout object treats each component in the container as a card. Only one card is visible at a
time.
3 FlowLayout
The FlowLayout is the default layout. It layout the components in a directional flow.
4 GridLayout
The GridLayout manages the components in the form of a rectangular grid.
5 GridBagLayout
This is the most flexible layout manager class. The object of GridBagLayout aligns the component
vertically, horizontally, or along their baseline without requiring the components of the same size.
6 GroupLayout
The GroupLayout hierarchically groups the components in order to position them in a Container.
7 SpringLayout
A SpringLayout positions the children of its associated container according to a set of constraints.
Swing Components: -
Swing components provide a rich set of tools for building graphical user interfaces (GUIs) in
Java. These components include text fields, text areas, buttons, check boxes, radio buttons,
lists, choices, scrollbars, windows, menus, and dialog boxes. Each component serves a
specific purpose in creating interactive and user-friendly interfaces.
Swing Components:
• Text Fields: Allow users to enter a single line of text.
• Text Areas: Provide a multi-line area for text input and display.
• Buttons: Trigger actions when clicked. According to DZone, they can display text
and/or images.
• Check Boxes: Allow users to select or deselect options.
• Radio Buttons: Allow users to select only one option from a group.
• Lists: Display a list of items, allowing users to select one or more.
• Choices (Combo Boxes): Combine a button or editable field with a dropdown list.
• Scrollbars: Enable users to navigate through content that exceeds the visible area of
a component.
• Windows: Top-level containers that display a window on the screen.
• Menus: Provide a list of commands or options, often associated with a menu bar.
• Dialog Boxes: Small windows used to interact with the user for specific tasks or to
display information.
Key Features of Swing:
• Lightweight Components:
Swing components are lightweight, meaning they are implemented in Java and don't rely on
the underlying operating system's GUI components.
• Pluggable Look and Feel:
Swing allows you to change the appearance of components to match different look and feel
themes, enhancing user experience.
• MVC Architecture:
Swing follows the Model-View-Controller (MVC) architectural pattern, which separates data,
presentation, and control logic, making code more organized and maintainable.
Difference between AWT and Swing:
S.NO AWT Swing
1. Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
applications in Java and is used to create various applications.
2. The components of Java AWT are The components of Java Swing are light
heavy weighted. weighted.
3. Java AWT has comparatively less Java Swing has more functionality as
functionality as compared to Swing. compared to AWT.
4. The execution time of AWT is more The execution time of Swing is less than
than Swing. AWT.
5. The components of Java AWT are The components of Java Swing are
platform dependent. platform independent.
6. MVC pattern is not supported by MVC pattern is supported by Swing.
AWT.
7. AWT provides comparatively less Swing provides more powerful
powerful components. components.
8 AWT components require java.awt Swing components requires javax.swing
package package
9 AWT is a thin layer of code on top of Swing is much larger swing also has very
the operating system. much richer functionality.
10 AWT stands for Abstract windows Swing is also called as JFC(java Foundation
toolkit . classes). It is part of oracle's JFC.
11 Using AWT , you have to implement Swing has them built in.
a lot of things yourself .
Example: AWT Button
java Ca
import java.awt.*;
import java.awt.event.*;
public class AWTExample {
public static void main(string[] args) {
Frame frame = new Frame("AWT Example");
Button button new Button("Click Me");
button.setBounds(100, 100, 80, 30);
button.addActionListener(e -> System.out.println("AWT Button Clicked"));
frame.add(button);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setvisible(true);
}
}
Example: Swing Button
java Copy Edit
import javax.swing.*;
public class SwingExample{
public static void main(string[] args) {
JFrame frame = new JFrame("Swing Example");
JButton button = new JButton("Click Me");
button.setBounds(100, 100, 100, 30);
button.addActionListener(e System.out.println("Swing Button Clicked"));
frame.add(button);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}