r22 Oop Java Unit 4 Notes 2026
r22 Oop Java Unit 4 Notes 2026
UNIT - IV : Event Handling: Events, Event sources, Event classes, Event Listeners,
Delegation event model,handling mouse and keyboard events, Adapter classes. The
AWT class hierarchy, user interface components- labels, button, canvas, scrollbars,
text components, check box, checkbox groups, choices, lists panels – scrollpane,
dialogs, menubar, graphics, layout manager – layout manager types – border,grid,
flow, card and grid bag.
1.1 Events
Examples:
Example Listeners:
Advantages:
EXAMPLE:
In Java AWT, mouse events are generated when the user interacts with the mouse —
for example:
Clicking a button
Moving the cursor
Dragging the mouse
Entering or exiting a component’s area
All mouse events are handled through the Delegation Event Model, using event classes
and listener interfaces.
There are three main listener interfaces for handling mouse events:
Method Description
Called when a mouse button is clicked (pressed and
mouseClicked(MouseEvent e)
released)
mousePressed(MouseEvent e) Called when a mouse button is pressed
mouseReleased(MouseEvent
Called when a mouse button is released
e)
mouseEntered(MouseEvent e) Called when the mouse enters a component
mouseExited(MouseEvent e) Called when the mouse exits a component
Method Description
mouseMoved(MouseEvent e) Called when the mouse is moved within a component
Called when the mouse is dragged (moved with button
mouseDragged(MouseEvent e)
pressed)
Method Description
mouseWheelMoved(MouseWheelEvent e) Called when the mouse wheel is rotated
To simplify coding, Java provides adapter classes that implement listener interfaces
with empty methods — so you can override only the needed ones.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
MouseListenerExample() {
// Frame Title
super("Mouse Listener and Mouse Motion Listener Example");
// Create a Label
label = new JLabel("Move or Click the Mouse Inside the Window");
label.setFont(new Font("Arial", Font.BOLD, 14));
label.setHorizontalAlignment(JLabel.CENTER);
// Add Listeners
addMouseListener(this);
addMouseMotionListener(this);
// Frame Settings
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
// MouseListener Methods
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")");
}
// MouseMotionListener Methods
public void mouseDragged(MouseEvent e) {
label.setText("Mouse Dragged at (" + e.getX() + ", " + e.getY() + ")");
}
// Main Method
public static void main(String[] args) {
new MouseListenerExample();
}
}
Output:
Displays a frame.
Shows messages like “Mouse Clicked at (x,y)” or “Mouse Entered” depending on
mouse actions.
import java.awt.*;
import java.awt.event.*;
MouseAdapterExample() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
msg = "Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")";
repaint();
}
});
setSize(400, 300);
setTitle("Mouse Adapter Example");
setVisible(true);
}
Output:
Prints “Mouse Clicked at (x, y)” on the frame when you click anywhere.
Key events in Java occur when a keyboard key is pressed, released, or typed.
These events are handled using the Delegation Event Model, just like mouse events.
When a key is pressed or released while a component has keyboard focus, a KeyEvent
is generated.
Class
Package Description
Name
Encapsulates information about keyboard actions (press,
KeyEvent java.awt.event
release, type).
KeyListener Interface
Method Description
keyPressed(KeyEvent e) Called when a key is pressed down.
keyReleased(KeyEvent
Called when a key is released.
e)
Called when a key is typed (pressed and released, generates a
keyTyped(KeyEvent e)
character).
Adapter Class
If you don’t want to implement all three methods, you can extend:
Method Description
getKeyChar() Returns the character associated with the key typed.
getKeyCode() Returns the integer key code for the key pressed.
getModifiersEx() Returns the modifier keys (like Shift, Ctrl, Alt).
Returns true if the key pressed is an action key (arrow keys,
isActionKey()
function keys).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
KeyListenerExample() {
super("KeyListener Example");
// Layout setup
setLayout(new FlowLayout());
add(label);
add(textField);
// Frame setup
setSize(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
// KeyListener Methods
public void keyTyped(KeyEvent e) {
label.setText("Key Typed: " + e.getKeyChar());
}
// Main Method
public static void main(String[] args) {
new KeyListenerExample();
}
}
Output Behavior:
import java.awt.*;
import java.awt.event.*;
KeyAdapterExample() {
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
msg = "Typed: " + e.getKeyChar();
repaint();
}
});
setSize(400, 300);
setTitle("Key Adapter Example");
setVisible(true);
}
Output Behavior:
In Java AWT, event handling is done using listener interfaces like MouseListener,
KeyListener, WindowListener, etc.
Each listener interface contains multiple methods, and if you implement the
interface, you must override all methods — even if you need only one.
Java provides Adapter Classes, which are abstract classes that implement listener
interfaces and provide empty implementations of all methods.
You can then extend the adapter class and override only the required methods.
Definition
Adapter class is an abstract class that provides default (empty) implementations for
all methods in an event listener interface.
Reason Explanation
To avoid writing unnecessary empty
Only override what you need
methods
Makes event handling concise and
To simplify code
readable
To improve clarity Focus only on relevant event methods
component.addListener(new AdapterClass() {
public void eventMethod(EventObject e) {
// event handling code
}
});
Here:
import java.awt.*;
import java.awt.event.*;
MouseAdapterExample() {
// Register MouseAdapter
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
msg = "Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")";
repaint();
}
});
setSize(400, 300);
setTitle("Mouse Adapter Example");
setVisible(true);
}
Explanation:
import java.awt.*;
import java.awt.event.*;
KeyAdapterExample() {
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
msg = "Typed: " + e.getKeyChar();
repaint();
}
});
setSize(400, 300);
setTitle("Key Adapter Example");
setVisible(true);
}
Explanation:
import java.awt.*;
import java.awt.event.*;
WindowAdapterExample() {
setSize(400, 300);
setTitle("Window Adapter Example");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.out.println("Window Closed!");
System.exit(0);
}
});
setVisible(true);
}
Explanation:
Advantage Description
Simplifies event handling No need to implement all interface methods
Cleaner code Avoids clutter of empty methods
Flexible Override only what you need
Reduces boilerplate Makes code short and readable
Each AWT GUI component is represented by a class, and all such classes form a
hierarchical structure — known as the AWT Class Hierarchy.
Here’s a simplified text diagram showing the main AWT class structure:
Object
└── Component
├── Container
│ ├── Panel
│ │ ├── Applet
│ │ ├── Canvas
│ │ └── ScrollPane
│ └── Window
│ ├── Frame
│ │ └── JFrame (Swing)
│ └── Dialog
│ └── FileDialog
├── Button
├── Label
├── TextComponent
│ ├── TextField
│ └── TextArea
├── List
├── Checkbox
├── Choice
├── Scrollbar
└── MenuComponent
├── MenuBar
├── Menu
├── MenuItem
└── CheckboxMenuItem
(a) java.lang.Object
The root of all Java classes.
Every AWT class ultimately inherits from Object.
(b) java.awt.Component
Superclass of all GUI components (buttons, labels, text fields, etc.).
Defines common properties such as:
o Position (setBounds, setLocation)
o Size (setSize, getWidth, getHeight)
o Visibility (setVisible)
o Colors and fonts (setBackground, setFont)
o Drawing (paint(Graphics g))
Example:
Button b = new Button("Click");
b.setBounds(50, 100, 80, 30);
(c) java.awt.Container
A subclass of Component.
A Container can hold other components (Buttons, Labels, Panels, etc.).
Common methods:
o add(Component c) – adds a component
o remove(Component c) – removes a component
o setLayout(LayoutManager lm) – sets layout
Example:
Frame f = new Frame("Example");
Button b = new Button("OK");
f.add(b);
(d) java.awt.Panel
Simplest container.
Used to group multiple components.
Panels do not have borders or titles.
Example:
Panel p = new Panel();
p.add(new Button("Submit"));
p.add(new Button("Cancel"));
(e) java.awt.Window
(f) java.awt.Frame
The main window for most AWT applications.
Has a title bar, menu bar, close/minimize buttons, etc.
Often used as the base container.
Example:
Frame f = new Frame("My Frame");
f.setSize(400, 300);
f.setVisible(true);
(g) java.awt.Dialog
A pop-up window used for short-term interactions with the user.
Can be modal (blocks parent) or non-modal.
Example:
Dialog d = new Dialog(f, "Message", true);
d.setSize(200, 100);
d.setVisible(true);
(h) java.awt.Canvas
A blank area used for custom drawing.
Commonly used with the Graphics class to draw shapes, images, or animations.
Example:
class MyCanvas extends Canvas {
public void paint(Graphics g) {
g.setColor(Color.RED);
g.fillOval(50, 50, 100, 100);
} }
(i) java.awt.ScrollPane
A container with scrollbars that automatically appear when content exceeds
view size.
(j) java.awt.TextComponent
An abstract superclass for text-based components.
o Subclasses:
TextField → Single-line input
TextArea → Multi-line input
Example:
TextField tf = new TextField("Enter Name");
TextArea ta = new TextArea("Enter Description", 5, 30);
(k) java.awt.Button
Represents a push button that generates an ActionEvent when clicked.
Example:
Button b = new Button("Submit");
(l) java.awt.Label
Used to display a line of read-only text.
Example:
Label l = new Label("Welcome to AWT!");
(m) java.awt.Checkbox
Allows true/false selection.
Can be grouped using CheckboxGroup to form radio buttons.
Example:
Checkbox c1 = new Checkbox("Java");
Checkbox c2 = new Checkbox("Python", true);
(n) java.awt.Choice
Example:
Choice ch = new Choice();
ch.add("C");
ch.add("C++");
ch.add("Java");
(o) java.awt.List
Displays a scrollable list of items.
Can allow single or multiple selection.
Example:
List list = new List(4, true);
list.add("Red");
list.add("Green");
list.add("Blue");
(p) java.awt.Scrollbar
Example:
Class Description
MenuBar Container for menus
Menu Represents a drop-down menu
MenuItem Represents an item in a menu
CheckboxMenuItem Menu item with a checkbox
1. Label
Label()
Label(String text)
Label(String text, int alignment)
Common Methods
Method Description
setText(String t) Changes the label text
getText() Returns label text
setAlignment(int align) Aligns text (Label.LEFT, CENTER, RIGHT)
import java.awt.*;
class LabelExample {
LabelExample() {
Frame f = new Frame("Label Example");
Label l1 = new Label("Welcome to Java AWT", Label.CENTER);
f.add(l1);
f.setSize(250, 100);
f.setVisible(true);
}
public static void main(String[] args) { new LabelExample(); }
}
2. Button
Button()
Button(String label)
Common Methods
Method Description
setLabel(String text) Sets button text
getLabel() Returns current label
addActionListener(ActionListener l) Registers event listener
Example
import java.awt.*;
import java.awt.event.*;
class ButtonExample {
ButtonExample() {
Frame f = new Frame("Button Example");
Button b = new Button("Click Me");
b.setBounds(80, 100, 80, 30);
b.addActionListener(e -> System.out.println("Button Clicked!"));
f.add(b);
f.setSize(250, 200);
f.setLayout(null);
f.setVisible(true);
}
3. Canvas
A blank drawing area where custom graphics can be drawn using the Graphics
class.
Important Methods
Method Description
paint(Graphics g) Draws on the canvas
repaint() Refreshes the drawing area
Example
import java.awt.*;
class CanvasExample extends Canvas {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(50, 50, 100, 80);
g.setColor(Color.RED);
g.drawOval(200, 60, 50, 50);
}
public static void main(String[] args) {
Frame f = new Frame("Canvas Example");
CanvasExample c = new CanvasExample();
f.add(c);
f.setSize(300, 250);
f.setVisible(true);
}
}
4. Scrollbar
Constructors
Scrollbar()
Scrollbar(int orientation) // HORIZONTAL or VERTICAL
Important Methods
Method Description
setValue(int v) Sets current scroll position
getValue() Returns scroll position
setMaximum(int m) Sets maximum value
Example
import java.awt.*;
class ScrollbarExample {
ScrollbarExample() {
Frame f = new Frame("Scrollbar Example");
Scrollbar sb = new Scrollbar(Scrollbar.VERTICAL, 0, 10, 0, 100);
f.add(sb);
f.setSize(200, 200);
f.setVisible(true);
}
public static void main(String[] args) { new ScrollbarExample(); }
}
5. Text Components
A. TextField
Method Description
setText(String s) Sets text
getText() Gets text
setEchoChar(char c) Masks text (e.g., passwords)
Example:
import java.awt.*;
class TextFieldExample {
TextFieldExample() {
Frame f = new Frame("TextField Example");
TextField tf = new TextField("Enter Name");
tf.setBounds(80, 100, 120, 30);
f.add(tf);
f.setSize(300, 200);
f.setLayout(null);
f.setVisible(true);
PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 22
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4
}
public static void main(String[] args) { new TextFieldExample(); }
}
B. TextArea
Method Description
append(String s) Adds text at end
setText(String s) Sets new text
getText() Returns text
Example:
import java.awt.*;
class TextAreaExample {
TextAreaExample() {
Frame f = new Frame("TextArea Example");
TextArea ta = new TextArea("Type here...", 5, 20);
f.add(ta);
f.setSize(300, 200);
f.setVisible(true);
}
public static void main(String[] args) { new TextAreaExample(); }
}
6. Checkbox
Common Methods
Method Description
getState() Returns true if selected
setState(boolean b) Sets checkbox state
getLabel() Returns label text
Example
import java.awt.*;
class CheckboxExample {
CheckboxExample() {
7. CheckboxGroup
Groups multiple checkboxes so that only one can be selected at a time (works
like Radio Buttons).
Example
import java.awt.*;
class CheckboxGroupExample {
CheckboxGroupExample() {
Frame f = new Frame("CheckboxGroup Example");
CheckboxGroup cg = new CheckboxGroup();
Checkbox c1 = new Checkbox("Male", cg, true);
Checkbox c2 = new Checkbox("Female", cg, false);
f.add(c1);
f.add(c2);
f.setLayout(new FlowLayout());
f.setSize(200, 150);
f.setVisible(true);
}
public static void main(String[] args) { new CheckboxGroupExample(); }
}
8. Choice
Method Description
add(String item) Adds an item
getSelectedItem() Returns selected item
getItem(int index) Returns item at index
Example:
import java.awt.*;
class ChoiceExample {
ChoiceExample() {
Frame f = new Frame("Choice Example");
Choice ch = new Choice();
ch.add("C");
ch.add("C++");
ch.add("Java");
ch.add("Python");
f.add(ch);
f.setLayout(new FlowLayout());
f.setSize(200, 150);
f.setVisible(true);
}
public static void main(String[] args) { new ChoiceExample(); }
}
9. List
Method Description
add(String item) Adds item
getSelectedItem() Returns selected item
getSelectedIndexes() Returns indices of selected items
Example:
import java.awt.*;
class ListExample {
ListExample() {
Frame f = new Frame("List Example");
List list = new List(4, true);
list.add("C");
list.add("C++");
list.add("Java");
list.add("Python");
f.add(list);
f.setSize(200, 200);
f.setVisible(true);
}
public static void main(String[] args) { new ListExample(); }
}
10. Panel
Example:
import java.awt.*;
class PanelExample {
PanelExample() {
Frame f = new Frame("Panel Example");
Panel p = new Panel();
p.add(new Button("OK"));
p.add(new Button("Cancel"));
f.add(p);
f.setSize(200, 150);
f.setVisible(true);
}
public static void main(String[] args) { new PanelExample(); }
}
11. ScrollPane
Example:
import java.awt.*;
class ScrollPaneExample {
ScrollPaneExample() {
Frame f = new Frame("ScrollPane Example");
TextArea ta = new TextArea("Scroll inside me", 5, 20);
ScrollPane sp = new ScrollPane();
sp.add(ta);
f.add(sp);
f.setSize(250, 200);
f.setVisible(true);
}
public static void main(String[] args) { new ScrollPaneExample(); }
}
12. Dialog
Example:
import java.awt.*;
class DialogExample {
DialogExample() {
Frame f = new Frame("Parent Frame");
Dialog d = new Dialog(f, "Dialog Example", true);
d.add(new Label("This is a dialog"));
d.setSize(200, 100);
f.setSize(300, 200);
f.setVisible(true);
d.setVisible(true);
}
public static void main(String[] args) { new DialogExample(); }
}
Class Purpose
MenuBar Holds menus
Menu Drop-down menu
MenuItem Item in a menu
Example:
import java.awt.*;
class MenuBarExample {
MenuBarExample() {
Frame f = new Frame("Menu Example");
MenuBar mb = new MenuBar();
Menu m = new Menu("File");
MenuItem mi1 = new MenuItem("Open");
MenuItem mi2 = new MenuItem("Save");
m.add(mi1); m.add(mi2);
mb.add(m);
f.setMenuBar(mb);
f.setSize(300, 200);
f.setVisible(true);
}
public static void main(String[] args) { new MenuBarExample(); }
}
14. Graphics
Method Description
drawLine(x1, y1, x2, y2) Draws a line
drawRect(x, y, w, h) Draws a rectangle
fillRect(x, y, w, h) Fills rectangle
drawOval(x, y, w, h) Draws oval
setColor(Color c) Sets drawing color
drawString(String, x, y) Draws text
Example:
import java.awt.*;
class GraphicsExample extends Frame {
public void paint(Graphics g) {
g.setColor(Color.RED);
g.drawRect(50, 50, 100, 50);
g.setColor(Color.BLUE);
g.fillOval(70, 120, 60, 60);
g.setColor(Color.BLACK);
g.drawString("AWT Graphics", 60, 220);
}
public static void main(String[] args) {
GraphicsExample g = new GraphicsExample();
g.setSize(250, 250);
g.setVisible(true);
}
}
Introduction
Layout Default
Description
Manager For
FlowLayout Arranges components in a row (like text flow) Panel
Divides container into 5 regions: North, South, East,
BorderLayout Frame
West, Center
GridLayout Arranges components in rows and columns —
CardLayout Displays one component (card) at a time —
GridBagLayout Most flexible, aligns components with different sizes —
1. FlowLayout
Constructor
Common Methods
Method Description
setAlignment(int align) Sets alignment (LEFT, CENTER, RIGHT)
setHgap(int h) Sets horizontal gap
setVgap(int v) Sets vertical gap
Example
import java.awt.*;
class FlowLayoutExample {
FlowLayoutExample() {
Frame f = new Frame("FlowLayout Example");
f.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 10));
for (int i = 1; i <= 5; i++)
f.add(new Button("Button " + i));
f.setSize(300, 150);
f.setVisible(true);
}
2. BorderLayout
Constructor
BorderLayout()
BorderLayout(int hgap, int vgap)
Methods
Method Description
add(Component c, Object constraint) Adds a component to a specific region
setHgap(int h) Sets horizontal gap
setVgap(int v) Sets vertical gap
Example
import java.awt.*;
class BorderLayoutExample {
BorderLayoutExample() {
Frame f = new Frame("BorderLayout Example");
f.setLayout(new BorderLayout(10, 10));
f.setSize(300, 200);
f.setVisible(true);
}
public static void main(String[] args) { new BorderLayoutExample(); }
}
3. GridLayout
Constructor
Methods
Method Description
setRows(int rows) Sets number of rows
setColumns(int cols) Sets number of columns
setHgap(int h) Sets horizontal gap
setVgap(int v) Sets vertical gap
Example
import java.awt.*;
class GridLayoutExample {
GridLayoutExample() {
Frame f = new Frame("GridLayout Example");
f.setLayout(new GridLayout(2, 3, 10, 10)); // 2 rows, 3 cols
f.setSize(300, 200);
f.setVisible(true);
}
public static void main(String[] args) { new GridLayoutExample(); }
}
4. CardLayout
Constructor
CardLayout()
CardLayout(int hgap, int vgap)
Method Description
next(Container parent) Shows next card
previous(Container parent) Shows previous card
show(Container parent, String name) Shows specific card by name
first(Container parent) Shows first card
last(Container parent) Shows last card
Example
import java.awt.*;
import java.awt.event.*;
class CardLayoutExample implements ActionListener {
Frame f;
CardLayout card;
Button b1, b2, b3;
CardLayoutExample() {
f = new Frame("CardLayout Example");
card = new CardLayout();
f.setLayout(card);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
f.add(b1, "1");
f.add(b2, "2");
f.add(b3, "3");
f.setSize(250, 150);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
card.next(f);
}
5. GridBagLayout
Constructor
GridBagLayout()
GridBagConstraints Fields
Field Description
gridx, gridy Position (column, row)
gridwidth, gridheight Number of cells spanned
weightx, weighty Resize proportion
fill How component fills space (BOTH, HORIZONTAL, VERTICAL)
insets Padding
anchor Alignment (CENTER, EAST, WEST, etc.)
Example
import java.awt.*;
class GridBagLayoutExample {
GridBagLayoutExample() {
Frame f = new Frame("GridBagLayout Example");
f.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0; gbc.gridy = 0;
f.add(b1, gbc);
gbc.gridx = 1; gbc.gridy = 0;
f.add(b2, gbc);
gbc.gridx = 0; gbc.gridy = 2;
f.add(b4, gbc);
gbc.gridx = 1; gbc.gridy = 2;
f.add(b5, gbc);
f.setSize(300, 200);
f.setVisible(true);
}
public static void main(String[] args) { new GridBagLayoutExample(); }
}
Summary Table
Layout
Arrangement Constructor Key Features
Manager
FlowLayout Left to right FlowLayout() Simple, wraps lines
NORTH, SOUTH, EAST,
BorderLayout 5 regions BorderLayout()
WEST, CENTER
GridLayout Rows × Columns GridLayout(r, c) Equal cell sizes
One component at a
CardLayout CardLayout() Used for tabbed/step screens
time
Grid with flexible
GridBagLayout GridBagLayout() Most powerful layout
sizes