0% found this document useful (0 votes)
4 views27 pages

Unit5 Java Swing Guide-1

This document provides a comprehensive guide to Java GUI programming using Swing, detailing the differences between AWT and Swing, key components, and layout management. It includes code examples for various components like JButton, JLabel, JTextField, and JTextArea, as well as event handling concepts. The document also emphasizes the importance of layout managers for responsive design and explains the Delegation Event Model for handling user interactions.

Uploaded by

richaroychd
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)
4 views27 pages

Unit5 Java Swing Guide-1

This document provides a comprehensive guide to Java GUI programming using Swing, detailing the differences between AWT and Swing, key components, and layout management. It includes code examples for various components like JButton, JLabel, JTextField, and JTextArea, as well as event handling concepts. The document also emphasizes the importance of layout managers for responsive design and explains the Delegation Event Model for handling user interactions.

Uploaded by

richaroychd
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

Unit 5 – Java

GUI
Programmin
g
with Swing
A Complete Beginner-Friendly Guide with Code
Examples

Department of AI & Data Sciences


Chandigarh Engineering College Jhanjeri
1. Introduction to GUI
GUI stands for Graphical User Interface. Instead of typing
commands (like in a terminal), a GUI lets users interact with a
program by clicking buttons, filling text boxes, selecting menus,
and so on.
Think of any app you use daily — WhatsApp, Chrome, MS
Word. They all have GUIs!

What is a GUI in Java?


Java provides two libraries to build GUIs:
• AWT (Abstract Window Toolkit) – the older library
• Swing – the modern, improved library (built on top of
AWT)

A GUI program in Java typically has:


• A Window (called a Frame)
• Components inside the window — buttons, labels, text
fields, etc.
• Events — actions that happen when the user does
something (clicks, types)

2. AWT (Abstract Window Toolkit) – Class


Hierarchy
AWT is the original Java GUI library, introduced in Java 1.0. It
talks directly to the operating system to draw components. This
makes it platform-dependent — the same program can look
different on Windows vs Mac.

AWT Class Hierarchy


Here is how AWT classes are organized (parent → child):

[Link]
└── Component ← Base class for all
visual elements
├── Button
├── Label
├── TextField
└── Container ← Can hold other
components
├── Panel
└── Window
└── Frame ← A top-level
window with title bar

Key AWT Classes


Class Purpose
Component Base class; all visual elements
extend this
Container A component that can hold
other components
Panel A simple container with no
border or title
Window A window without title bar or
menu bar
Frame A full window with title bar,
close button, etc.
Button A clickable button
Label Displays static text
TextField Single-line text input

3. Introduction to Swing
Swing is part of Java Foundation Classes (JFC). It was
introduced in Java 1.2 to fix AWT's problems. Swing is built ON
TOP of AWT — it uses AWT under the hood but draws its own
components instead of relying on the OS.

💡 Note: Swing components are 'lightweight' — they are drawn


by Java itself, not the OS. This means they look the same on
every platform!

Key Features of Swing


• Platform independent (same look everywhere)
• More components than AWT (trees, tables, tabbed panes,
etc.)
• Pluggable Look and Feel — you can change the visual
theme
• All Swing component names start with the letter J (e.g.,
JButton, JLabel)

4. Swing vs AWT – Comparison


Here is a clear side-by-side comparison of Swing and AWT:
Feature AWT
Feature Swing
Platform Dependence Platform dependent (OS
draws it)
Platform independent (Java
draws it)
Components Fewer components
Many more components
(JTable, JTree, etc.)
Look & Feel Looks different on each OS
Consistent look everywhere
Weight Heavyweight (uses OS
resources)
Lightweight (uses Java to
render)
Package [Link]
[Link]
Naming Button, Label, TextField
JButton, JLabel, JTextField
Speed Slightly faster (uses native
code)
Slightly slower but more
flexible

5. Hierarchy of Swing Components


Swing follows a clear inheritance chain. Every Swing
component ultimately extends from Java's Object class.

[Link]
└── [Link] ← All visual
elements
└── [Link] ← Can hold other
components
└── JComponent ← Base class for
all Swing components
├── JButton
├── JLabel
├── JTextField
├── JTextArea
├── JPanel
└── ... many more

Top-Level Containers (do NOT extend JComponent):


├── JFrame ← Main application window
├── JDialog ← Pop-up dialog window
└── JApplet ← For browser-based apps
(deprecated)

💡 Note: JFrame, JDialog, and JApplet are top-level


containers. They extend Window (AWT) directly, not
JComponent. All other Swing components extend
JComponent.

6. Important Swing Components


Let us look at each major Swing component, what it does, and
a code example.

6.1 JButton – Clickable Button


A JButton is a push button that the user can click to trigger an
action.

import [Link].*;

public class ButtonDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("JButton Example");
JButton btn = new JButton("Click Me!");
[Link](100, 100, 120, 40);
[Link](btn);
[Link](350, 250);
[Link](null);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}
📤 Output:
┌─────────────────────────────────┐
│ JButton Example │
│ │
│ [ Click Me! ] │
│ │
└─────────────────────────────────┘

6.2 JLabel – Display Text or Image


A JLabel displays a non-editable text or image on the screen.

import [Link].*;

public class LabelDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("JLabel Example");
JLabel label = new JLabel("Hello, I am a
Label!");
[Link](50, 80, 250, 30);
[Link](label);
[Link](350, 220);
[Link](null);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}
📤 Output:
┌─────────────────────────────────┐
│ JLabel Example │
│ │
│ Hello, I am a Label! │
│ │
└─────────────────────────────────┘

6.3 JTextField – Single Line Text Input


A JTextField lets the user type a single line of text.

import [Link].*;

public class TextFieldDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("JTextField
Example");
JLabel label = new JLabel("Enter Name:");
JTextField tf = new JTextField();
[Link](30, 80, 100, 30);
[Link](140, 80, 150, 30);
[Link](label);
[Link](tf);
[Link](350, 220);
[Link](null);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}
📤 Output:
┌─────────────────────────────────┐
│ JTextField Example │
│ │
│ Enter Name: [_____________] │
│ │
└─────────────────────────────────┘

6.4 JTextArea – Multi-line Text Input


A JTextArea lets the user type multiple lines of text. It is often
wrapped in a JScrollPane to add scrollbars.

import [Link].*;

public class TextAreaDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("JTextArea
Example");
JTextArea ta = new JTextArea("Type here...");
JScrollPane sp = new JScrollPane(ta); //
adds scrollbars
[Link](30, 30, 280, 120);
[Link](sp);
[Link](350, 220);
[Link](null);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}
📤 Output:
┌─────────────────────────────────┐
│ JTextArea Example │
│ ┌─────────────────────────┐ │
│ │ Type here... │▲ │
│ │ │ │
│ │ │▼ │
│ └─────────────────────────┘ │
└─────────────────────────────────┘
7. A Simple Complete Swing Application
Let us now build a complete Swing application step by step.
Here we create a login form with a name field, password field,
and a submit button.

Steps to Create a Swing Application


1. Import the [Link] package
2. Create a class and extend JFrame (or create a JFrame
object)
3. Create the GUI components (buttons, labels, fields)
4. Add components to the frame
5. Set frame size and make it visible

import [Link].*;
import [Link].*;

public class SimpleSwingApp extends JFrame {

SimpleSwingApp() {
// Step 3: Create components
JLabel lblName = new JLabel("Username:");
JLabel lblPass = new JLabel("Password:");
JTextField tfName = new JTextField();
JPasswordField pfPass = new JPasswordField();
JButton btnLogin = new JButton("Login");

// Step 4: Position components (x, y, width,


height)
[Link](30, 50, 90, 30);
[Link](130, 50, 150, 30);
[Link](30, 100, 90, 30);
[Link](130, 100, 150, 30);
[Link](120, 150, 90, 35);

// Add to frame
add(lblName); add(tfName);
add(lblPass); add(pfPass);
add(btnLogin);

// Step 5: Configure frame


setTitle("Login Form");
setSize(350, 250);
setLayout(null); // null layout =
absolute positioning
setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new SimpleSwingApp(); // Step 2: Create
frame
}
}
📤 Output:
┌──────────────────────────────┐
│ Login Form │
│ │
│ Username: [______________] │
│ │
│ Password: [**************] │
│ │
│ [ Login ] │
└──────────────────────────────┘

8 & 9. Layout Management


Instead of manually positioning every component using
setBounds(), Java provides Layout Managers that
automatically arrange components for you. This is the
recommended approach because it handles window resizing
gracefully.

💡 Note: With null layout, components don't resize when you


resize the window. Layout managers handle this automatically.

8.1 FlowLayout – Left to Right


Components are placed one after another from left to right.
When the row is full, it wraps to the next row — just like text in
a paragraph.

import [Link].*;
import [Link].*;

public class FlowLayoutDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Demo");
[Link](new FlowLayout()); // Set
FlowLayout

[Link](new JButton("Button 1"));


[Link](new JButton("Button 2"));
[Link](new JButton("Button 3"));
[Link](new JButton("Button 4"));
[Link](new JButton("Button 5"));

[Link](300, 150);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}
📤 Output:
┌──────────────────────────────────┐
│ FlowLayout Demo │
│ [Button 1] [Button 2] [Button 3]│
│ [Button 4] [Button 5] │
└──────────────────────────────────┘

8.2 BorderLayout – Five Regions


BorderLayout divides the container into 5 areas: NORTH (top),
SOUTH (bottom), EAST (right), WEST (left), and CENTER.
You place components in these named zones.

import [Link].*;
import [Link].*;

public class BorderLayoutDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("BorderLayout
Demo");
[Link](new BorderLayout()); //
Default for JFrame

[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](350, 250);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}
📤 Output:
┌─────────────────────────────┐
│ [ NORTH ] │
│ [WEST] [ CENTER ] [E] │
│ [ SOUTH ] │
└─────────────────────────────┘

8.3 GridLayout – Rows and Columns


GridLayout arranges components in a grid of equal-sized cells.
You specify the number of rows and columns.

import [Link].*;
import [Link].*;

public class GridLayoutDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Demo");
// 2 rows, 3 columns
[Link](new GridLayout(2, 3));

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


[Link](new JButton("Cell " + i));
}

[Link](350, 200);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}
📤 Output:
┌───────────────────────────────────┐
│ GridLayout Demo │
│ [ Cell 1 ] [ Cell 2 ] [ Cell 3] │
│ [ Cell 4 ] [ Cell 5 ] [ Cell 6] │
└───────────────────────────────────┘

10 & 11. Event Handling


Event handling makes your GUI interactive. Without it, buttons
do nothing when clicked. Event handling lets you define what
SHOULD happen when a user interacts with components.

Key Concepts
Term Meaning
Event An action the user performs
(click, type, move mouse)
Event Source The component where the
event happened (e.g., a
JButton)
Event Class A Java object describing the
event (e.g., ActionEvent)
Event Listener An interface you implement to
handle the event

Simple Button Click Example


Here we handle a button click using ActionListener. When the
button is clicked, a message appears in the label.

import [Link].*;
import [Link].*; // import event classes

public class EventDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("Event Handling
Demo");
JButton btn = new JButton("Click Me");
JLabel label = new JLabel("Nothing clicked
yet.");

[Link](100, 60, 120, 35);


[Link](60, 120, 250, 30);

// ★ Register an ActionListener on the button


[Link](new ActionListener() {
public void actionPerformed(ActionEvent
e) {
// This runs when button is clicked
[Link]("Button was clicked!");
}
});

[Link](btn);
[Link](label);
[Link](350, 220);
[Link](null);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}
📤 Output:
Before click: After click:
┌────────────────────────┐
┌────────────────────────┐
│ Event Handling Demo │ │ Event Handling
Demo │
│ │ │

│ [ Click Me ] │ → │ [ Click
Me ] │
│ │ │

│ Nothing clicked yet. │ │ Button was
clicked! │
└────────────────────────┘
└────────────────────────┘

12. Delegation Event Model


Java uses the Delegation Event Model for handling events.
The idea is: the event source does NOT handle the event itself.
Instead, it DELEGATES (passes) the event to a registered
listener.

How it works:

1. User clicks a button



2. JButton generates an ActionEvent object

3. JButton passes (delegates) it to the registered
ActionListener

4. ActionListener's actionPerformed() method is
called

5. Your code inside actionPerformed() runs!

Full Delegation Model Example


Here we show all three parts clearly: Source (JButton),
Listener (ActionListener), and Event (ActionEvent).

import [Link].*;
import [Link].*;

// Step 1: Create a Listener class


class MyListener implements ActionListener {
JLabel resultLabel;

MyListener(JLabel lbl) {
[Link] = lbl;
}

// Step 4: Handle the event here


public void actionPerformed(ActionEvent e) {
[Link]("Event received from: " +
[Link]().getClass().getSimpleName());
}
}

public class DelegationDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("Delegation
Model");
JButton btn = new JButton("Fire Event");
JLabel lbl = new JLabel("Waiting...");

[Link](100, 60, 130, 35);


[Link](40, 120, 280, 30);

// Step 2: Register listener on source (btn)


[Link](new MyListener(lbl));

[Link](btn); [Link](lbl);
[Link](350, 220);
[Link](null);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}
📤 Output:
After clicking [Fire Event]:
┌─────────────────────────────────────┐
│ Delegation Model │
│ [ Fire Event ] │
│ Event received from: JButton │
└─────────────────────────────────────┘

13. Mouse and Key Events


13.1 Mouse Events
Mouse events are triggered when the user does something
with the mouse. Java provides the MouseListener interface
with 5 methods:

Method When it fires


mouseClicked() Mouse button pressed and
released at same spot
mousePressed() Mouse button is pressed down
mouseReleased() Mouse button is released
mouseEntered() Mouse cursor enters the
component area
mouseExited() Mouse cursor leaves the
component area

import [Link].*;
import [Link].*;

public class MouseEventDemo extends JFrame implements


MouseListener {

JLabel status;

MouseEventDemo() {
status = new JLabel("Move or click mouse
here...");
[Link](30, 80, 300, 30);
add(status);

// Register 'this' as the mouse listener on


the frame
addMouseListener(this);

setTitle("Mouse Events");
setSize(380, 220);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void mouseClicked(MouseEvent e) {


[Link]("Clicked at (" + [Link]() + ",
" + [Link]() + ")");
}
public void mousePressed(MouseEvent e)
{ [Link]("Mouse Pressed!"); }
public void mouseReleased(MouseEvent e)
{ [Link]("Mouse Released!"); }
public void mouseEntered(MouseEvent e)
{ [Link]("Mouse Entered window"); }
public void mouseExited(MouseEvent e)
{ [Link]("Mouse Exited window"); }
public static void main(String[] args) { new
MouseEventDemo(); }
}
📤 Output:
When user clicks at position (150, 80):
┌──────────────────────────────────────┐
│ Mouse Events │
│ │
│ Clicked at (150, 80) │
│ │
└──────────────────────────────────────┘

13.2 Key Events


Key events are triggered when the user presses or releases
keyboard keys. Java provides the KeyListener interface:

Method When it fires


keyPressed() A key is pressed down
keyReleased() A key is released
keyTyped() A character key is typed
(pressed and released)

import [Link].*;
import [Link].*;

public class KeyEventDemo extends JFrame implements


KeyListener {

JLabel status;
JTextField tf;

KeyEventDemo() {
JLabel lbl = new JLabel("Type in the box:");
[Link](30, 40, 150, 30);

tf = new JTextField();
[Link](30, 80, 200, 35);

status = new JLabel("Key status will appear


here");
[Link](30, 130, 300, 30);

[Link](this); // attach listener


to text field

add(lbl); add(tf); add(status);


setTitle("Key Events");
setSize(370, 230);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void keyPressed(KeyEvent e) {


[Link]("Key Pressed: " +
[Link]());
}
public void keyReleased(KeyEvent e) {
[Link]("Key Released: " +
[Link]());
}
public void keyTyped(KeyEvent e) {
[Link]("Key Typed: " +
[Link]());
}

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


KeyEventDemo(); }
}
📤 Output:
When user types 'A':
┌──────────────────────────────────────┐
│ Key Events │
│ Type in the box: │
│ [A_____________________] │
│ Key Typed: A │
└──────────────────────────────────────┘
14. Adapter Classes
There is a problem with listener interfaces: if an interface has 5
methods, you MUST implement ALL 5 even if you only need 1.
This creates a lot of empty, useless code.

💡 Note: Adapter classes solve this problem! They provide


empty (do-nothing) implementations of all interface methods.
You just extend the Adapter and override ONLY the methods
you need.

Common Adapter Classes


Adapter Class Replaces Interface
MouseAdapter MouseListener (5 methods)
MouseMotionAdapter MouseMotionListener (2
methods)
KeyAdapter KeyListener (3 methods)
WindowAdapter WindowListener (7 methods)
FocusAdapter FocusListener (2 methods)

Without Adapter (ugly – must implement all 5


methods)
// BAD WAY: implementing MouseListener directly
[Link](new MouseListener() {
public void mouseClicked(MouseEvent e) { /* I
need this */ }
public void mousePressed(MouseEvent e) { /*
empty - don't need */ }
public void mouseReleased(MouseEvent e) { /*
empty - don't need */ }
public void mouseEntered(MouseEvent e) { /*
empty - don't need */ }
public void mouseExited(MouseEvent e) { /*
empty - don't need */ }
});

With MouseAdapter (clean – override only what you


need)
import [Link].*;
import [Link].*;

public class AdapterDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("Adapter Class
Demo");
JButton btn = new JButton("Hover or Click
Me");
JLabel lbl = new JLabel("Status: ready");

[Link](80, 60, 180, 40);


[Link](60, 120, 260, 30);

// GOOD WAY: extend MouseAdapter, override


only what you need
[Link](new MouseAdapter() {
// Override only mouseClicked — others
are handled by adapter
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Status: Button
clicked!");
}

@Override
public void mouseEntered(MouseEvent e) {
[Link]("Status: Mouse is
hovering!");
}

@Override
public void mouseExited(MouseEvent e) {
[Link]("Status: Mouse left
button");
}
// mousePressed and mouseReleased handled
by MouseAdapter (empty)
});

[Link](btn); [Link](lbl);
[Link](360, 220);
[Link](null);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}
📤 Output:
On mouse hover over button:
┌────────────────────────────────────┐
│ Adapter Class Demo │
│ │
│ [ Hover or Click Me ] │
│ │
│ Status: Mouse is hovering! │
└────────────────────────────────────┘

On click:
┌────────────────────────────────────┐
│ Status: Button clicked! │
└────────────────────────────────────┘

KeyAdapter Example
Using KeyAdapter to detect only the Enter key, ignoring all
other key events:

import [Link].*;
import [Link].*;

public class KeyAdapterDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("KeyAdapter Demo");
JTextField tf = new JTextField();
JLabel lbl = new JLabel("Press Enter after
typing");

[Link](30, 50, 280, 35);


[Link](30, 110, 300, 30);

// Extend KeyAdapter – only override


keyPressed
[Link](new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if ([Link]() ==
KeyEvent.VK_ENTER) {
[Link]("You typed: " +
[Link]());
}
}
// keyReleased and keyTyped handled by
KeyAdapter (empty)
});

[Link](tf); [Link](lbl);
[Link](360, 200);
[Link](null);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}
📤 Output:
User types 'Hello World' and presses Enter:
┌──────────────────────────────────────┐
│ KeyAdapter Demo │
│ [Hello World___________________] │
│ You typed: Hello World │
└──────────────────────────────────────┘
Quick Reference Summary – Unit 5

Topic Key Class / Interface Purpose


AWT Frame, Button, Label OS-dependent
GUI (older)
Swing JFrame, JButton, JLabel Platform-
independent GUI
(modern)
JButton [Link] Clickable push
button
JLabel [Link] Non-editable text
or image
JTextField [Link] Single-line text
input
JTextArea [Link] Multi-line text
input
FlowLayout [Link] Left-to-right
arrangement
BorderLayou [Link] N/S/E/W/
t CENTER
regions
GridLayout [Link] Grid of equal
cells
ActionListen [Link] Handle button
er ner clicks
MouseListen [Link] Handle mouse
er er events (5
methods)
KeyListener [Link] Handle keyboard
events
MouseAdapt [Link] Adapter for
er r MouseListener
KeyAdapter [Link] Adapter for
KeyListener

You might also like