0% found this document useful (0 votes)
21 views10 pages

Java GUI Event-Driven Programming Guide

The document provides an overview of Java GUI programming, focusing on the use of AWT and Swing for creating graphical user interfaces. It explains event-driven programming, detailing how user actions trigger events and how these events are handled through listeners and event objects. Additionally, it covers various GUI components, layout managers, and includes examples of handling events in Java Swing applications.

Uploaded by

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

Java GUI Event-Driven Programming Guide

The document provides an overview of Java GUI programming, focusing on the use of AWT and Swing for creating graphical user interfaces. It explains event-driven programming, detailing how user actions trigger events and how these events are handled through listeners and event objects. Additionally, it covers various GUI components, layout managers, and includes examples of handling events in Java Swing applications.

Uploaded by

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

Java GUI and Event-Driven Programming

1. Introduction to GUI (Graphical User Interface)

Definition

A Graphical User Interface (GUI) is a type of user interface that allows users to interact with software
applications through graphical components such as buttons, menus, text boxes, and icons — instead of
typing commands on a console.

In Java, GUI applications are commonly created using:

 AWT (Abstract Window Toolkit) — older, platform-dependent.

 Swing — newer, lightweight, and platform-independent toolkit.

2. GUI Frameworks in Java

i. AWT (Abstract Window Toolkit)

 Introduced in early Java versions.

 Uses native OS components (platform-dependent).

 Limited in look and feel.

Example:

import [Link].*;

public class AwtExample {

public static void main(String[] args) {

Frame frame = new Frame("AWT Example");

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

[Link](btn);

[Link](300, 200);

[Link](new FlowLayout());

[Link](true);

}
ii. Swing

 Built on top of AWT, but is platform-independent.

 All components start with the prefix J (e.g., JButton, JLabel, JFrame).

 Supports modern GUIs with menus, tables, trees, etc.

 Provides more flexibility and appearance customization.

Example:

import [Link].*;

public class SwingExample {

public static void main(String[] args) {

JFrame frame = new JFrame("Swing Example");

JButton button = new JButton("Click Me");

[Link](button);

[Link](300, 200);

[Link](null);

[Link](100, 70, 100, 30);

[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);

NB: Swing applications are event-driven — they wait for users to interact with components such as
buttons or text fields.

3. Components of a Java GUI Application

Component Description Example

JFrame Main window container Holds other components

JButton A clickable button new JButton("Submit")

JLabel Displays text or images new JLabel("Name:")

JTextField Accepts single-line text input new JTextField(20)

JTextArea Accepts multi-line text input new JTextArea()


Component Description Example

JCheckBox Checkbox for true/false selection new JCheckBox("Accept")

JComboBox Drop-down list new JComboBox(items)

JPanel Container for organizing components Used for grouping

4. Layout Managers

Layout Managers control how components are arranged in a container (e.g., a JFrame or JPanel).

Layout Manager Description Example

FlowLayout Places components left-to-right, like text. Toolbar-like layout

Typical window
BorderLayout Divides container into 5 regions: North, South, East, West, Center.
layout

GridLayout Divides container into equal rows and columns. Calculator layout

Example – BorderLayout

import [Link].*;

import [Link].*;

public class BorderLayoutDemo {

public static void main(String[] args) {

JFrame frame = new JFrame("BorderLayout Example");

[Link](new BorderLayout());

[Link](new JButton("North"), [Link]);

[Link](new JButton("South"), [Link]);

[Link](new JButton("East"), [Link]);

[Link](new JButton("West"), [Link]);

[Link](new JButton("Center"), [Link]);


[Link](400, 250);

[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);

Event-Driven Programming

Now that we can build GUIs with Swing, the next question is:

How do these graphical components respond when a user clicks a button, types text, or closes the
window?

This leads us to the concept of Event-Driven Programming.

6. Event-Driven Programming

Definition

Event-driven programming is a paradigm where the flow of the program is controlled by user actions
(events) rather than a fixed sequence of code.

Common events include:

 Mouse click

 Key press

 Window closing

 Selection change

NB. In GUI programs, events are at the heart of interactivity.

The Java Event Delegation Model

Java uses a Delegation Event Model for handling events. It involves three key elements:

Component Role Example

Event Source The object that generates the event Button, TextField

Event Object Encapsulates event details ActionEvent, MouseEvent

Event Listener Object that receives and processes the event ActionListener, MouseListener
How It Works

1. The user performs an action (e.g., clicks a button).

2. The event source generates an event object (like ActionEvent).

3. The event object is sent to the listener registered with that source.

4. The listener’s method executes to respond to that event.

Diagrammatically:

User Action → Event Source → Event Object → Event Listener → Event Handler Code

7. Handling Events in Java Swing

Example 1: Button Click Event

import [Link].*;

import [Link].*;

public class ButtonEventExample {

public static void main(String[] args) {

JFrame frame = new JFrame("Event Example");

JButton button = new JButton("Click Me");

[Link](100, 100, 120, 40);

[Link](button);

[Link](350, 250);

[Link](null);

[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);

// Register an event listener

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {


[Link](null, "Button Clicked!");

});

Explanation:

 The JButton is the event source.

 The ActionEvent is the event object.

 The ActionListener is the listener.

 The code inside actionPerformed() is the event handler.

Example 2: Text Input and Button Interaction

import [Link].*;

import [Link].*;

public class GreetingApp {

public static void main(String[] args) {

JFrame frame = new JFrame("Greeting App");

JLabel label = new JLabel("Enter your name:");

JTextField textField = new JTextField();

JButton button = new JButton("Greet");

JLabel output = new JLabel("");

[Link](30, 30, 150, 25);

[Link](150, 30, 150, 25);

[Link](100, 80, 100, 30);

[Link](50, 130, 300, 25);

[Link](label); [Link](textField); [Link](button); [Link](output);


[Link](350, 250);

[Link](null);

[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);

// Handle button click

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

String name = [Link]();

[Link]("Hello, " + name + "! Welcome to Event-Driven Programming.");

});

Demonstrates interaction between multiple components.

8. Common Event Listener Interfaces

Listener Interface Event Type Example Source Component

ActionListener Button click JButton, JMenuItem

MouseListener Mouse events JPanel, JLabel

KeyListener Keyboard actions JTextField

ItemListener Checkbox or combo box selection JCheckBox, JComboBox

WindowListener Window open/close JFrame

Example 3: Mouse Listener

import [Link].*;

import [Link].*;
public class MouseEventExample extends JFrame implements MouseListener {

JLabel label;

MouseEventExample() {

label = new JLabel("Move or Click the Mouse");

[Link](60, 80, 200, 30);

add(label);

addMouseListener(this);

setSize(300, 200);

setLayout(null);

setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public void mouseClicked(MouseEvent e) { [Link]("Mouse Clicked"); }

public void mouseEntered(MouseEvent e) { [Link]("Mouse Entered"); }

public void mouseExited(MouseEvent e) { [Link]("Mouse Exited"); }

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

public static void main(String[] args) {

new MouseEventExample();

9. Advantages of Event-Driven Programming

1. Interactive: Users control the flow of the program.


2. Flexible: Handles multiple event types in real-time.

3. Modular: Each event handler can be designed independently.

4. Reusable Components: Buttons, panels, etc., can be reused.

5. Better User Experience: Enables dynamic, responsive applications.

10. Classroom Exercise

Task:
Create a GUI application that:

 Has a JTextField for entering your age.

 When you click a button labeled “Check Age,” it displays:

o “You are a minor” if under 18

o “You are an adult” otherwise.

Use ActionListener and if statements.

11. Summary

Concept Meaning / Role

GUI User-friendly interface using graphics

Event Action performed by user/system

Event Source Object that generates event

Event Object Carries details of the event

Listener Handles and responds to event

Handler Code executed when event occurs

ADDITIONAL MATERIALS

Using an IDE (Recommended for Teaching)

If you’re teaching and want your students to learn easily and visualize outputs fast, use a Java IDE:

Using NetBeans
1. Open NetBeans → File → New Project → Java Application.

2. Name the project (e.g., EventDemo).

3. Delete the default code and paste your Swing code inside the main () method.

4. Click the Run ▶️button — the GUI window appears.

implement a simple Login Form GUI that:

 Accepts username and password input.

 Has a Login button that triggers an event when clicked.

 Validates credentials and shows a message accordingly.

[Link]

You might also like