0% found this document useful (0 votes)
34 views34 pages

r22 Oop Java Unit 4 Notes 2026

Uploaded by

santhosh kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views34 pages

r22 Oop Java Unit 4 Notes 2026

Uploaded by

santhosh kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

OBJECT ORIENTED PROGRAMMING THROUGH JAVA

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. Event Handling in Java

1.1 Events

 An event is an object that describes a change in the state of a source.


 Events are generated when a user interacts with GUI components
 Button clicked
 Mouse moved
 Key pressed
 Window closing

1.2 Event Sources


 The source is the object that generates an event.
 Example: A button generates an ActionEvent when clicked.

1.3 Event Classes

 Java provides event classes in the java.awt.event package.

 Examples:

Event Class Description


ActionEvent Generated when a button is clicked or an item is selected
Generated by mouse actions (click, enter, exit, press,
MouseEvent
release)
KeyEvent Generated when a key is pressed, released, or typed
Generated when a window is opened, closed, activated,
WindowEvent
minimized
ItemEvent Generated when a checkbox / list is selected

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 1


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

1.4 Event Listeners

Listeners are interfaces that define methods to handle events.

 Listener objects receive and handle events.


 Must implement listener interfaces from java.awt.event.

Example Listeners:

Listener Interface Event Type Example Method

ActionListener ActionEvent actionPerformed(ActionEvent e)

MouseListener MouseEvent mouseClicked, mousePressed

MouseMotionListener MouseEvent mouseMoved, mouseDragged

KeyListener KeyEvent keyPressed, keyReleased

WindowListener WindowEvent windowClosing, windowOpened

2. Delegation Event Model

Introduced in Java 1.1


Event source delegates event handling to listener objects

Advantages:

 clear separation between source and handling logic.


 Separate event handling code from UI code
 Allows multiple listeners to listen to same source

 Java uses delegation event model:


1. An event is generated by a source.
2. Sent to one or more listeners.
3. Listener handles it.

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 2


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

EXAMPLE:

Button b = new Button("Click Me");


b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});

2. Handling Mouse and Keyboard Events

Handling Mouse Events in Java AWT

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.

2. Mouse Event Classes

Class Package Description


Describes events like mouse click, press, release,
MouseEvent java.awt.event
enter, exit, move, drag
MouseWheelEvent java.awt.event Describes mouse wheel rotation events

3. Mouse Listener Interfaces

There are three main listener interfaces for handling mouse events:

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 3


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4
Interface Purpose Main Methods
mouseClicked, mousePressed,
Detects clicks, press,
MouseListener mouseReleased, mouseEntered,
release, enter, and exit
mouseExited
Detects movement and
MouseMotionListener mouseMoved, mouseDragged
dragging
Detects scrolling of mouse
MouseWheelListener mouseWheelMoved
wheel

4. Methods of Mouse Event Interfaces

(a) MouseListener Methods

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

(b) MouseMotionListener Methods

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)

(c) MouseWheelListener Method

Method Description
mouseWheelMoved(MouseWheelEvent e) Called when the mouse wheel is rotated

5. Adapter Classes (for Mouse Events)

To simplify coding, Java provides adapter classes that implement listener interfaces
with empty methods — so you can override only the needed ones.

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 4


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

Adapter Class Implements


MouseAdapter MouseListener, MouseMotionListener
MouseMotionAdapter MouseMotionListener
MouseWheelAdapter MouseWheelListener

Example 1: Handling Mouse Events using MouseListener ,MouseMotionListener

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseListenerExample extends JFrame implements MouseListener,


MouseMotionListener {
JLabel label;

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 Label to Frame


add(label);

// 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() + ")");
}

public void mousePressed(MouseEvent e) {


label.setText("Mouse Pressed");
}

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 5


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

public void mouseReleased(MouseEvent e) {


label.setText("Mouse Released");
}

public void mouseEntered(MouseEvent e) {


label.setText("Mouse Entered the Frame");
getContentPane().setBackground(Color.LIGHT_GRAY);
}

public void mouseExited(MouseEvent e) {


label.setText("Mouse Exited the Frame");
getContentPane().setBackground(Color.WHITE);
}

// MouseMotionListener Methods
public void mouseDragged(MouseEvent e) {
label.setText("Mouse Dragged at (" + e.getX() + ", " + e.getY() + ")");
}

public void mouseMoved(MouseEvent e) {


label.setText("Mouse Moved 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.

Example 2: Using MouseAdapter (Simplified Approach)

import java.awt.*;
import java.awt.event.*;

public class MouseAdapterExample extends Frame

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 6


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

String msg = "";

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);
}

public void paint(Graphics g) {


g.drawString(msg, 100, 150);
}

public static void main(String[] args) {


new MouseAdapterExample();
}
}

Output:

 Prints “Mouse Clicked at (x, y)” on the frame when you click anywhere.

Key Event Handling in Java AWT

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.

Key Event Class

Class
Package Description
Name
Encapsulates information about keyboard actions (press,
KeyEvent java.awt.event
release, type).

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 7


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

KeyListener Interface

Interface Package Purpose


KeyListener java.awt.event Used to receive keyboard events (press, release, type).

Methods of 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:

Adapter Class Implements


KeyAdapter KeyListener

This allows overriding only the methods you need.

Useful Methods of KeyEvent Class

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).

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 8


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

Example 1: Handling Key Events using KeyListener

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class KeyListenerExample extends JFrame implements KeyListener {


JLabel label;
JTextField textField;

KeyListenerExample() {
super("KeyListener Example");

// Create label and text field


label = new JLabel("Type something in the text field...");
label.setFont(new Font("Arial", Font.BOLD, 14));
label.setHorizontalAlignment(JLabel.CENTER);

textField = new JTextField(20);


textField.addKeyListener(this); // Register KeyListener

// 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());
}

public void keyPressed(KeyEvent e) {


label.setText("Key Pressed: " + e.getKeyChar());
}

public void keyReleased(KeyEvent e) {


label.setText("Key Released: " + e.getKeyChar());
}

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 9


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

// Main Method
public static void main(String[] args) {
new KeyListenerExample();
}
}
Output Behavior:

 When a key is pressed → shows “Key Pressed: a”


 When released → “Key Released: a”
 When typed → “Key Typed: a”

Example 2: Using KeyAdapter (Simplified)

import java.awt.*;
import java.awt.event.*;

public class KeyAdapterExample extends Frame {

String msg = "";

KeyAdapterExample() {
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
msg = "Typed: " + e.getKeyChar();
repaint();
}
});

setSize(400, 300);
setTitle("Key Adapter Example");
setVisible(true);
}

public void paint(Graphics g) {


g.drawString(msg, 150, 150);
}

public static void main(String[] args) {


new KeyAdapterExample();
}
}

Output Behavior:

 Displays the character of the key you typed.

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 10


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

Adapter Classes in Java AWT

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.

Purpose of Adapter Classes

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

List of Common Adapter Classes in AWT

Adapter Class Implements Interface(s) Used For


MouseListener, Handling mouse events (click,
MouseAdapter
MouseMotionListener move, drag)
Handling only mouse motion
MouseMotionAdapter MouseMotionListener
events
MouseWheelAdapter MouseWheelListener Handling mouse wheel rotation
KeyAdapter KeyListener Handling keyboard events
FocusAdapter FocusListener Handling focus gained/lost events
Handling window
WindowAdapter WindowListener
open/close/minimize events
Handling component resize/move
ComponentAdapter ComponentListener
events
Handling component
ContainerAdapter ContainerListener
added/removed in a container

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 11


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

Syntax of Using an Adapter Class

component.addListener(new AdapterClass() {
public void eventMethod(EventObject e) {
// event handling code
}
});

Here:

 component → GUI element (like Button, Frame, etc.)


 addListener() → method to register listener
 AdapterClass → specific adapter (like MouseAdapter)
 eventMethod() → overridden method (like mouseClicked)

Example 1: Using MouseAdapter

import java.awt.*;
import java.awt.event.*;

public class MouseAdapterExample extends Frame {

String msg = "";

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);
}

public void paint(Graphics g) {


g.drawString(msg, 100, 150);
}

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 12


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

public static void main(String[] args) {


new MouseAdapterExample();
}
}

Explanation:

 We extended MouseAdapter anonymously.


 Only mouseClicked() is overridden — others are ignored.
 Output: Displays coordinates where mouse is clicked.

Example 2: Using KeyAdapter

import java.awt.*;
import java.awt.event.*;

public class KeyAdapterExample extends Frame {

String msg = "";

KeyAdapterExample() {
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
msg = "Typed: " + e.getKeyChar();
repaint();
}
});

setSize(400, 300);
setTitle("Key Adapter Example");
setVisible(true);
}

public void paint(Graphics g) {


g.drawString(msg, 150, 150);
}

public static void main(String[] args) {


new KeyAdapterExample();
}
}

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 13


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

Explanation:

 Only keyTyped() method is implemented.


 Displays the typed character on the frame.

Example 3: Using WindowAdapter

import java.awt.*;
import java.awt.event.*;

public class WindowAdapterExample extends Frame {

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);
}

public static void main(String[] args) {


new WindowAdapterExample();
}
}

Explanation:

 WindowAdapter handles only windowClosing() method.


 The program exits when the window is closed.

Advantages of Adapter Classes

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

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 14


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

4. AWT CLASS HIERARCHY (Abstract Window Toolkit)

 AWT (Abstract Window Toolkit) is Java’s GUI framework (Graphical User


Interface).
 It allows developers to create windows, buttons, text boxes, menus, etc.
 AWT is part of the java.awt package and relies on the native GUI of the operating
system.

Each AWT GUI component is represented by a class, and all such classes form a
hierarchical structure — known as the AWT Class Hierarchy.

Top-Level Hierarchy Diagram

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

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 15


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

Explanation of Each Class Level

(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"));

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 16


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

(e) java.awt.Window

 A top-level container with no borders or title bar.


 Subclasses: Frame, Dialog.

(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

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 17


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

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

 A drop-down list that allows the user to select one item.

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");

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 18


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

(p) java.awt.Scrollbar

 Provides horizontal or vertical scrolling control.

Example:

Scrollbar sb = new Scrollbar(Scrollbar.VERTICAL, 0, 10, 0, 100);

(q) java.awt.MenuComponent (and Subclasses)

Used for creating menus and menu bars.

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

USER INTERFACE COMPONENTS IN AWT (Abstract Window Toolkit)

1. Label

 Used to display static text that the user cannot edit.


 Class: java.awt.Label

Common Constructors

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)

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 19


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4
Example

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

 Represents a push button.


 Generates an ActionEvent when clicked.

Common Constructors

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);
}

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 20


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

public static void main(String[] args)


{ new ButtonExample(); }
}

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

 Allows the user to scroll horizontally or vertically.


 Class: java.awt.Scrollbar

Constructors

Scrollbar()
Scrollbar(int orientation) // HORIZONTAL or VERTICAL

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 21


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

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

 Used for single-line input.

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

 Used for multi-line text input.

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

 Represents true/false options.


 Can be independent or grouped as radio buttons using CheckboxGroup.

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() {

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 23


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4
Frame f = new Frame("Checkbox Example");
Checkbox c1 = new Checkbox("Java");
Checkbox c2 = new Checkbox("Python", true);
f.add(c1);
f.add(c2);
f.setLayout(new FlowLayout());
f.setSize(200, 150);
f.setVisible(true);
}
public static void main(String[] args) { new 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

 A drop-down menu (single selection).

Method Description
add(String item) Adds an item
getSelectedItem() Returns selected item
getItem(int index) Returns item at index

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 24


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

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

 Displays a scrollable list of items.

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(); }
}

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 25


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

10. Panel

 A container to group multiple components together.

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

 Provides automatic scrolling for large components.

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

 A pop-up window that asks for input or shows information.

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 26


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

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(); }
}

13. MenuBar, Menu, MenuItem

Used for menus in a Frame.

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(); }
}

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 27


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

14. Graphics

 Provides drawing capability — lines, shapes, text, images.


 Accessed inside the paint(Graphics g) method.

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);
}
}

LAYOUT MANAGERS IN JAVA AWT

Introduction

 Layout managers are used to control the positioning and sizing of


components inside a container (like Frame, Panel, etc.).
 Each container (like Frame or Panel) has a default layout manager.
 Layout managers automatically adjust components when the window is
resized.

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 28


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

2. Commonly Used Layout Managers

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

 Arranges components in a single row, wrapping to the next line if needed.


 Components are centered by default.

Constructor

FlowLayout() // default (center alignment)


FlowLayout(int align) // LEFT, CENTER, RIGHT
FlowLayout(int align, int hgap, int vgap)

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);
}

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 29


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4
public static void main(String[] args) { new FlowLayoutExample(); }
}

2. BorderLayout

 Divides container into five regions:


o NORTH, SOUTH, EAST, WEST, CENTER

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.add(new Button("North"), BorderLayout.NORTH);


f.add(new Button("South"), BorderLayout.SOUTH);
f.add(new Button("East"), BorderLayout.EAST);
f.add(new Button("West"), BorderLayout.WEST);
f.add(new Button("Center"), BorderLayout.CENTER);

f.setSize(300, 200);
f.setVisible(true);
}
public static void main(String[] args) { new BorderLayoutExample(); }
}

3. GridLayout

 Divides the container into a grid of equal-sized cells.


 Each cell holds exactly one component.

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 30


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

Constructor

GridLayout(int rows, int cols)


GridLayout(int rows, int cols, int hgap, int vgap)

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

for (int i = 1; i <= 6; i++)


f.add(new Button("Button " + i));

f.setSize(300, 200);
f.setVisible(true);
}
public static void main(String[] args) { new GridLayoutExample(); }
}

4. CardLayout

 Treats each component as a card in a stack.


 Only one card is visible at a time.
 Used for switching between screens (like login → main menu).

Constructor

CardLayout()
CardLayout(int hgap, int vgap)

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 31


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4
Methods

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 = new Button("Card 1");


b2 = new Button("Card 2");
b3 = new Button("Card 3");

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);
}

public static void main(String[] args) { new CardLayoutExample(); }


}

Each click switches to the next card (button) using card.next().

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 32


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4

5. GridBagLayout

 The most flexible and complex layout manager.


 Allows components of different sizes to be placed in a grid-like structure.
 Works with a helper class GridBagConstraints to specify positions.

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();

Button b1 = new Button("Button 1");


Button b2 = new Button("Button 2");
Button b3 = new Button("Button 3");
Button b4 = new Button("Button 4");
Button b5 = new Button("Button 5");

gbc.fill = GridBagConstraints.HORIZONTAL;

gbc.gridx = 0; gbc.gridy = 0;
f.add(b1, gbc);

gbc.gridx = 1; gbc.gridy = 0;
f.add(b2, gbc);

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 33


OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-4
gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 2;
f.add(b3, 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

PREPARED BY B.VEERA PRATHAP , ASSISTANT PROFESSOR , CSE DEPARTMENT , SSIT 34

You might also like