List
import [Link];
import [Link];
// Student class
class Student {
// Private data members
private String usn;
private String name;
// Constructor
public Student(String usn, String name) {
[Link] = usn;
[Link] = name;
// Getter methods
public String getUsn() {
return usn;
public String getName() {
return name;
// Main class
public class StudentListDemo {
public static void main(String[] args) {
// Creating List using ArrayList
List<Student> studentList = new ArrayList<>();
// Adding at least 3 Student objects
[Link](new Student("1RV23CS001", "Rahul"));
[Link](new Student("1RV23CS002", "Sneha"));
[Link](new Student("1RV23CS003", "Arjun"));
// Displaying student data
[Link]("Student Details:");
for (Student s : studentList) {
[Link]("USN: " + [Link]() + ", Name: " + [Link]());
}
Java Swing in Java
Swing is a part of Java used to develop Graphical User Interface (GUI) applications.
It is included in the package:
[Link]
Swing provides ready-made components like buttons, labels, text fields, tables, menus, etc., to
build desktop applications.
Why Swing is Used?
Swing is used to create:
Desktop applications
Login forms
Banking systems
Student management systems
Text editors
Rich Set of Components
Provides advanced components like:
JButton
JLabel
JTextField
JTable
JMenu
JFrame
Customizable
You can change color, font, size, layout, etc.
Supports MVC Architecture
Swing internally follows Model–View–Controller design.
| Component | Purpose |
| -------------- | -------------------- |
| `JFrame` | Main window |
| `JLabel` | Display text |
| `JButton` | Button |
| `JTextField` | Text input |
| `JTextArea` | Multi-line text |
| `JCheckBox` | Checkbox |
| `JRadioButton` | Radio button |
| `JTable` | Display tabular data |
import [Link].*;
public class SimpleSwingExample {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Swing Program");
JButton button = new JButton("Click Me");
[Link](100, 100, 100, 40);
[Link](button);
[Link](300, 300);
[Link](null);
[Link](true);
}
}
Example for Model–View–Controller (MVC)
One simple and clear example of MVC is an Online Shopping Application.
Example: Online Shopping System
1. Model
The Model represents the data and business logic.
Example:
Product details (productId, name, price, stock)
Database operations (add product, update stock)
class Product {
private int id;
private String name;
private double price;
// constructor + getters
}
The Model handles:
Storing product data
Calculating total price
Updating inventory
2. View
The View is the user interface.
Example:
Web page showing product list
Displaying price and product details
Showing order confirmation
The View:
Displays data from Model
Does NOT contain business logic
Example output on screen:
Product Name: Laptop
Price: ₹50000
3. Controller
The Controller acts as a mediator between Model and View.
Example:
When user clicks "Add to Cart"
Controller receives request
Updates Model
Refreshes View
class ProductController {
public void addToCart(Product p) {
// business logic
}
}
How MVC Works (Flow)
1. User interacts with View
2. View sends request to Controller
3. Controller updates Model
4. Model sends updated data to View
5. View displays updated result
Key Features of Java Swing
Swing is a part of Java used to develop desktop GUI applications such as calculators, editors,
banking systems, etc.
Platform Independent
Swing is platform independent because it is written completely in Java.
Java programs run on JVM (Java Virtual Machine), which is available for multiple operating
systems.
✔ The same Swing program runs on Windows, Linux, and macOS
✔ No need to rewrite code for different OS
✔ Follows "Write Once, Run Anywhere" principle
This makes Swing suitable for cross-platform desktop applications.
Customizable
Swing allows developers to modify the appearance and behavior of components.
You can:
Change font type, size, and style
Change background and foreground colors
Add icons to buttons
Set borders and tooltips
Example:
[Link]([Link]);
[Link](new Font("Arial", [Link], 16));
This flexibility helps in designing attractive and user-friendly interfaces.
Extensible
Swing components can be extended (inherited) to create new custom components.
For example:
Create a custom button with special effects
Create a customized text field with validation
class MyButton extends JButton {
// Add custom features here
}
Because Swing follows object-oriented principles, it is easy to extend and reuse components.
Configurable
Swing supports Look and Feel (L&F), which means the appearance of components can be
changed without modifying core logic.
Common Look and Feel options:
Metal (Default)
Nimbus
System Look and Feel
Example:
[Link]("[Link]");
This allows developers to make the application look like:
✔ Windows style
✔ Mac style
✔ Custom theme
Lightweight
Swing components are called lightweight because:
They are written entirely in Java
They do not rely on native operating system GUI components
They are drawn using Java code
Unlike AWT (which uses native OS components), Swing components are platform-independent
and more flexible.
This reduces dependency on system resources and improves consistency across platforms.
Abstract Window Toolkit (AWT) in Java
AWT (Abstract Window Toolkit) is Java’s original GUI (Graphical User Interface) framework,
introduced in early versions of Java.
It provides classes to create windows, buttons, text fields, menus, and other GUI components.
Key Features of AWT
1. Platform-dependent (Heavyweight)
AWT components depend on the native operating system’s GUI components.
Example: A Button in Windows looks like a Windows button; in Linux, it looks
different.
Why AWT Depends on Native OS Components
The Abstract Window Toolkit (AWT) in Java uses something called peer-based
architecture.
🔹 What Does it Mean?
When you create an AWT component like:
Button b = new Button("Click");
Java does not draw the button itself.
Instead:
1. Java calls the operating system.
2. The OS creates its own native button.
3. Java links (connects) to that native button.
This native object is called a peer.
What is a Peer?
A peer is a platform-specific GUI component created by the operating system.
For example:
On Windows → It uses a Windows button.
On Linux → It uses a Linux system button.
On macOS → It uses a macOS button.
So the appearance and behavior depend on the OS.
Why is AWT Called Heavyweight?
Because:
It relies on OS-level components.
Each component occupies an actual native screen resource.
It consumes more system resources.
That is why AWT components are called heavyweight components.
Advantages of OS Dependency
✔ Native look and feel
✔ Faster in some cases
✔ Direct system integration
🔹 Disadvantages
❌ Platform-dependent behavior
❌ Inconsistent look across systems
❌ Limited customization
❌ Fewer components
2. Part of [Link] package
3. Uses native peer components
Each AWT component has a corresponding OS-level component (called a peer).
4. Basic Components Available
Detailed Difference Between AWT and Swing
No Feature AWT Swing
1 Full Form Abstract Window Toolkit Part of Java Foundation Classes (JFC)
2 Package [Link] [Link]
3 Component Type Heavyweight Lightweight
Platform
4 Platform-dependent Platform-independent
Dependency
Uses native OS
5 OS Dependency Written completely in Java
components
6 Look and Feel Native OS look only Pluggable Look & Feel
Uses peer-based Does not rely on native peers (except top-
7 Peer Architecture
architecture level containers)
Does not strictly follow
8 MVC Architecture Follows MVC architecture
MVC
Number of
9 Limited Rich and advanced
Components
10 Customization Limited customization Highly customizable
Slightly faster (native
11 Performance Slightly slower (pure Java rendering)
components)
12 Portability Less portable Highly portable
No advanced controls like Provides JTable, JTree, JTabbedPane,
13 Advanced Controls
table/tree etc.
Top-Level
14 Frame, Dialog JFrame, JDialog, JWindow
Containers
15 Component Naming Button, Label, TextField JButton, JLabel, JTextField
16 Event Handling Delegation Event Model Same model (improved handling)
17 Layout Managers Basic layout managers Same + better flexibility
18 Consistency UI differs across OS Same UI across all platforms
Introduced in early Java
19 Development Era Introduced in Java 1.2
versions
Rarely used in new
20 Modern Usage Preferred for desktop applications
applications
Heavyweight vs Lightweight
AWT → Uses actual OS window objects → Heavyweight
Swing → Drawn by Java itself → Lightweight
Why Swing is Preferred?
More components
Better customization
Consistent UI
Supports advanced GUI features
Simple AWT Example Simple Swing Example
import [Link].*; import [Link].*;
public class AWTExample { public class SwingExample {
public static void main(String[] args) { public static void main(String[] args) {
Frame f = new Frame("AWT Window"); JFrame f = new JFrame("Swing
Window");
Button b = new Button("Click Me");
[Link](100,100,80,30); JButton b = new JButton("Click Me");
[Link](100,100,120,40);
[Link](b);
[Link](300,300); [Link](b);
[Link](null); [Link](300,300);
[Link](true); [Link](null);
} [Link](true);
} }}
Button b = new Button("Click"); JButton b = new JButton("Click");
The operating system creates the button. Java itself draws the button.
Appearance changes based on the OS. Same appearance on all systems
Components and Containers
In Java Swing, graphical user interfaces are built using components and containers. These
form the basic building blocks for designing windows and interactive elements.
1. Components in Java Swing
Components are the individual GUI elements that the user can see and interact with, such as
buttons, labels, text fields, etc.
Definition
A component is a visual control used to display information or receive input from the user.
Examples of Swing Components
JButton – Creates a clickable button
JLabel – Displays text or images
JTextField – Allows single-line text input
JTextArea – Allows multi-line text input
JCheckBox – Provides a selectable checkbox
JRadioButton – Allows selection of one option among many
JComboBox – Creates a drop-down list
2. Containers in Java Swing
A container is a component that can hold other components.
Definition
A container is used to organize and manage the layout of components in a GUI.
“The layout manager decides where each component should appear and how much space it
occupies.”
Common Layout Managers in Java
FlowLayout – places components from left to right.
BorderLayout – divides the container into North, South, East, West, Center.
GridLayout – arranges components in rows and columns.
CardLayout – shows one component at a time like cards.
Types of Containers
1. Top-Level Containers
These provide the main window for the application.
Examples:
JFrame – Main application window
JDialog – Dialog window
JApplet – Applet container (legacy)
2. Intermediate Containers
These are used to group components inside top-level containers.
Examples:
JPanel – Generic container for grouping components
JScrollPane – Adds scrollbars to components
JSplitPane – Divides components into two parts
JTabbedPane – Provides tabbed views
1. JFrame – Main Application Window
Example: A main window with a button.
import [Link].*;
public class JFrameExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Main Window");
JButton button = new JButton("Click");
[Link](button);
[Link](300,200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
2. JDialog – Dialog Window
Example: A popup dialog box.
import [Link].*;
public class JDialogExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
JDialog dialog = new JDialog(frame, "Dialog Box");
[Link](new JLabel("This is a dialog"));
[Link](200,150);
[Link](true);
}
}
3. JApplet – Applet Container
Example: Simple applet.
import [Link].*;
import [Link].*;
public class JAppletExample extends JApplet {
public void init() {
add(new JLabel("Hello Applet"));
}
}
4. JPanel – Grouping Components
Example: Grouping buttons in a panel.
import [Link].*;
public class JPanelExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
[Link](new JButton("OK"));
[Link](new JButton("Cancel"));
[Link](panel);
[Link](300,200);
[Link](true);
}
}
import [Link].*;
public class ContainerExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Container Example");
JPanel panel = new JPanel();
JButton b1 = new JButton("OK");
JButton b2 = new JButton("Cancel");
[Link](b1);
[Link](b2);
[Link](panel);
[Link](300,200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
The Swing Packages
In Java Swing, Swing packages provide classes used to create Graphical User Interfaces (GUI)
in Java applications. These packages contain components, containers, layout managers, and
event-handling classes required to design GUI programs.
Main Swing Packages
1. [Link]
This is the core Swing package that contains most of the GUI components.
Purpose:
Provides lightweight components used to build graphical interfaces.
Common Classes:
JFrame – Main window of an application
JPanel – Container used to group components
JButton – Push button component
JLabel – Displays text or images
JTextField – Single-line text input
JTextArea – Multi-line text input
JCheckBox – Checkbox component
JRadioButton – Radio button component
JComboBox – Drop-down list
JTable – Table component
2. [Link]
This package contains event classes and listener interfaces used for handling Swing events.
Purpose:
Handles user interactions such as clicking buttons or selecting menu items.
Examples:
TableModelListener
ChangeListener
3. [Link]
This package provides classes for drawing borders around Swing components.
Purpose:
Enhances the visual appearance of GUI components.
Examples:
LineBorder
TitledBorder
4. [Link]
This package contains classes used to create and manage tables in Swing applications.
Purpose:
Supports advanced table features like sorting, editing, and custom rendering.
Examples:
JTable
5. [Link]
This package supports tree-structured components.
Purpose:
Used to represent hierarchical data.
Examples:
JTree
TreeModel
DefaultMutableTreeNode
6. [Link]
This package provides classes for advanced text handling.
Purpose:
Supports styled text, document models, and text editing features.
Examples:
Document
StyledDocument
JTextComponent
Event Handling
Event Handling in Java Swing refers to the mechanism that allows a program to respond to
user interactions such as button clicks, mouse movements, and keyboard input in
applications written in Java.
Definition
Event handling is the process of detecting and responding to events generated by user actions or
system events in a GUI application.
An event occurs when the user interacts with a component, such as clicking a button or typing in
a text field.
Components of Event Handling
1. Event Source
The event source is the component that generates the event.
Examples:
JButton
JTextField
JCheckBox
Example:
When a user clicks a button, the button generates an event.
2. Event Object
The event object contains information about the event that occurred.
Example classes:
ActionEvent
MouseEvent
KeyEvent
3. Event Listener
The event listener is an interface that receives and processes the event.
Examples:
ActionListener
MouseListener
KeyListener
A listener must implement methods to handle events.
Steps in Event Handling
1. Create the GUI component (event source).
2. Implement the listener interface.
3. Register the listener with the component.
4. Override the event-handling method.
import [Link].*;
import [Link].*;
public class EventExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Event Handling Example");
JButton button = new JButton("Click Me");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked!");
}
});
[Link](button);
[Link](300,200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);
}
}
Output
When the user clicks the button, the message “Button Clicked!” is printed in the console.
Listener Purpose
ActionListener Handles button click events
MouseListener Handles mouse actions
KeyListener Handles keyboard input
ItemListener Handles checkbox or combo box selection
WindowListener Handles window events
Advantages of Event Handling
Enables interactive GUI applications
Allows programs to respond to user actions
Improves user experience
Supports modular programming