Unit 5: Event Driven Programming




Event Driven Programming 

Event Driven Programming is a programming style where the flow of the program depends on user actions (events).

Simple meaning: The program waits for an event, and when the event happens, it responds.

Examples of Events:

  • Clicking a button
  • Moving the mouse
  • Pressing a key
  • Closing a window

Real-life example:

  • Pressing a doorbell → Bell rings
  • Clicking “Submit” → Form gets submitted

Java supports event-driven programming mainly through AWT and Swing.

Graphics Programming in Java

Graphics programming is used to draw shapes, text, images, and colors on the screen.

Java provides graphics support using:

  • AWT (Abstract Window Toolkit)
  • Swing
  • Graphics and Graphics2D classes

Frame

A Frame is a main window that appears on the screen.

Simple meaning: A frame is like an empty window where we place buttons, labels, drawings, etc.

Example:

import java.awt.*; class MyFrame extends Frame { MyFrame() { setTitle("My First Frame"); setSize(400, 300); setVisible(true); } public static void main(String args[]) { new MyFrame(); } }

Key Points:

  • Frame belongs to java.awt
  • It has title bar, borders, and close button
  • Acts as a container for components

Components

Components are GUI elements placed inside a frame.

Examples of Components:

  • Button
  • Label
  • TextField
  • Checkbox
  • Choice

Example:

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

Common AWT Components:

ComponentUse
ButtonClick action
LabelDisplay text
TextFieldInput text
CheckboxSelect option
ChoiceDrop-down list

Working with 2D Shapes

Java uses the Graphics and Graphics2D classes to draw shapes.

Drawing Shapes

Shapes are drawn inside the paint() method.

Example:

public void paint(Graphics g) { g.drawLine(50, 50, 200, 50); g.drawRect(50, 80, 100, 60); g.drawOval(50, 160, 100, 60); }

Common Shape Methods:

MethodShape
drawLine()Line
drawRect()Rectangle
fillRect()Filled rectangle
drawOval()Oval
drawArc()Arc

Using Graphics2D (Advanced 2D Graphics)

Graphics2D g2 = (Graphics2D) g;

Additional Features:

  • Better quality
  • Rotation
  • Scaling
  • Stroke thickness

Using Colors

Setting Colors

Java provides the Color class.

Example:

g.setColor(Color.RED); g.fillRect(50, 50, 100, 50);

Custom Colors:

Color c = new Color(100, 150, 200); g.setColor(c);

Common Colors:

  • Color.RED
  • Color.BLUE
  • Color.GREEN
  • Color.BLACK

Using Fonts

A font controls:

  • Text style
  • Text size
  • Text appearance

Example:

Font f = new Font("Arial", Font.BOLD, 20); g.setFont(f); g.drawString("Hello Java", 50, 50);

Font Styles:

  • Font.PLAIN
  • Font.BOLD
  • Font.ITALIC

Using Images

Loading and Displaying Images

Java uses the Image and Toolkit classes.

Example:

Image img = Toolkit.getDefaultToolkit().getImage("image.jpg"); g.drawImage(img, 50, 50, this);

Uses:

  • Logos
  • Icons
  • Background images

Event Handling (Basic Overview)

Event Handling Steps:

  1. Generate event (button click)
  2. Listener listens to event
  3. Listener handles event

Example:

b.addActionListener(e -> { System.out.println("Button Clicked"); });

Common Event Listeners:

  • ActionListener
  • MouseListener
  • KeyListener
  • WindowListener

Complete Simple Example

import java.awt.*; class GraphicsDemo extends Frame { GraphicsDemo() { setSize(400, 300); setVisible(true); } public void paint(Graphics g) { g.setColor(Color.BLUE); g.drawRect(50, 50, 100, 60); g.setFont(new Font("Arial", Font.BOLD, 18)); g.drawString("Java Graphics", 50, 150); } public static void main(String args[]) { new GraphicsDemo(); } }

Conclusion

Event-driven and graphics programming in Java allow developers to:

  • Create interactive applications
  • Build graphical user interfaces
  • Draw shapes, text, and images
  • Respond to user actions

Understanding frames, components, 2D shapes, colors, fonts, and images is essential for GUI-based Java applications and exams.

Basics of Event Handling in Java

Event handling is the mechanism that allows a Java program to respond to user actions.

Simple meaning: When a user performs an action, Java detects it as an event and handles it using code.

Examples of Events:

  • Clicking a button
  • Pressing a key
  • Moving the mouse
  • Closing a window

Event Handling Mechanism in Java

Java follows the Delegation Event Model.

Components of Event Handling:

  1. Event Source – Object that generates the event (Button, TextField, Frame)
  2. Event Object – Contains details of the event (ActionEvent, MouseEvent)
  3. Event Listener (Handler) – Object that handles the event

Event Handlers (Event Listeners)

An event handler is a method that executes when an event occurs.

Example: ActionListener

import java.awt.*; import java.awt.event.*; class MyFrame extends Frame implements ActionListener { Button b; MyFrame() { b = new Button("Click"); add(b); b.addActionListener(this); setSize(300,200); setVisible(true); } public void actionPerformed(ActionEvent e) { System.out.println("Button clicked"); } }

Key Points:

  • Listener interface must be implemented
  • Event-handling method must be overridden

What are Adapter Classes?

Adapter classes provide empty implementations of listener interfaces.

Problem Without Adapter: Some listeners have many methods, even if you need only one.

Solution: Adapter classes allow overriding only required methods.

Example: MouseAdapter

import java.awt.event.*; class MyMouse extends MouseAdapter { public void mouseClicked(MouseEvent e) { System.out.println("Mouse clicked"); } }

Common Adapter Classes:

Adapter ClassListener
MouseAdapterMouseListener
KeyAdapterKeyListener
WindowAdapterWindowListener

Action Events

An ActionEvent occurs when:

  • Button is clicked
  • Menu item selected
  • Enter key pressed in TextField

Example:

b.addActionListener(e -> { System.out.println("Action performed"); });

Class Used:

java.awt.event.ActionEvent

Mouse Events

Mouse events occur when the user interacts with the mouse.

Types of Mouse Events:

Event MethodDescription
mouseClicked()Mouse clicked
mousePressed()Button pressed
mouseReleased()Button released
mouseEntered()Cursor enters
mouseExited()Cursor exits

Example:

addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { System.out.println("Mouse Clicked at " + e.getX()); } });

AWT Event Hierarchy

Java events follow a hierarchical structure.

Object ↓ EventObject ↓ AWTEvent ↓ ActionEvent, MouseEvent, KeyEvent, WindowEvent

Explanation:

  • EventObject → Base class for all events
  • AWTEvent → Base class for AWT events
  • Subclasses represent specific events

Introduction to Swing

Swing is a GUI toolkit built on top of AWT.

Key Features of Swing:

  • Platform independent
  • Lightweight components
  • More advanced and flexible than AWT

Difference Between AWT and Swing

FeatureAWTSwing
ComponentsHeavyweightLightweight
Look & FeelOS dependentPlatform independent
Component namesButtonJButton

Layout Management in Swing

What is Layout Manager?

A layout manager controls how components are arranged inside a container.

Simple meaning: It decides where buttons, labels, and text fields appear.

Common Layout Managers

1. FlowLayout - Components arranged in a row

setLayout(new FlowLayout());

2. BorderLayout - Divides container into five areas

add(button, BorderLayout.NORTH);
Area
NORTH
SOUTH
EAST
WEST
CENTER

3. GridLayout - Components arranged in rows and columns

setLayout(new GridLayout(2, 2));

4. BoxLayout - Components arranged vertically or horizontally

Example: Swing Layout

import javax.swing.*; class SwingDemo { public static void main(String args[]) { JFrame f = new JFrame("Swing Layout"); JButton b1 = new JButton("One"); JButton b2 = new JButton("Two"); f.setLayout(new FlowLayout()); f.add(b1); f.add(b2); f.setSize(300,200); f.setVisible(true); } }

Conclusion

Event handling and Swing form the foundation of Java GUI programming.
They help to:

  • Build interactive applications
  • Handle user input efficiently
  • Design well-structured interfaces

Understanding event handlers, adapter classes, action and mouse events, AWT event hierarchy, and Swing layout management is essential for Java exams and practical applications.