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

Module 3

Swing is built on top of AWT, extending its functionality by providing lightweight and customizable GUI components. Swing components, such as JButton, inherit from AWT classes, relying on AWT for core architecture while offering advanced features. The document also discusses the MVC architecture in Swing, event handling mechanisms, custom painting, and the use of JLabel and ImageIcon.
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)
4 views50 pages

Module 3

Swing is built on top of AWT, extending its functionality by providing lightweight and customizable GUI components. Swing components, such as JButton, inherit from AWT classes, relying on AWT for core architecture while offering advanced features. The document also discusses the MVC architecture in Swing, event handling mechanisms, custom painting, and the use of JLabel and ImageIcon.
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

Discuss how Swing is built on AWT.

Illustrate your
answer with an example showing how a basic Swing
component is dependent on AWT classes. (10 Marks)
Introduction

Swing is a part of the Java Foundation Classes (JFC) introduced in JDK 1.2. It is not a complete
replacement for AWT (Abstract Window Toolkit); instead, it is built on top of AWT and extends its
functionality by providing a richer set of GUI components. Swing components are lightweight,
platform-independent, and highly customizable.

How Swing is Built on AWT

●​ AWT provides the basic framework for GUI development in Java.


●​ Swing uses AWT’s event handling mechanism, layout managers, and windowing system.
●​ Swing components inherit from the JComponent class, which is ultimately derived from
AWT classes.
●​ Thus, Swing relies on AWT for its core architecture while adding advanced GUI features.

Class Hierarchy
Object
|
Component (AWT)
|
Container (AWT)
|
JComponent (Swing)
|
JButton, JLabel, JTextField

The hierarchy shows that Swing components are dependent on AWT classes such as
Component and Container.

AWT and Swing Component Comparison

AWT Component Swing Component


Button JButton

TextField JTextField

Label JLabel

Swing components are enhanced versions of AWT components.

Example Showing Dependency on AWT


import [Link].*;

public class SwingDemo {


public static void main(String args[]) {

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

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

[Link](button);

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

[Link](JFrame.EXIT_ON_CLOSE);
}
}

Explanation

●​ JButton is a Swing component.


●​ JButton inherits from JComponent.
●​ JComponent inherits from AWT classes Container and Component.
●​ Therefore, although JButton belongs to Swing, it ultimately depends on AWT classes
for its functionality.

Advantages of Swing over AWT

1.​ Lightweight components.


2.​ Platform-independent appearance.
3.​ Rich set of GUI controls.
4.​ Pluggable Look and Feel (PLAF).
5.​ Greater customization and extensibility.

Conclusion

Swing is built on top of AWT and extends its capabilities by providing lightweight and
feature-rich GUI components. It utilizes AWT’s core classes, event handling, and layout
management system while offering a more flexible and consistent user interface across different
platforms.

Last-Minute Exam Revision (2 Lines)

Swing extends AWT and uses its event handling, containers, and windowing system.
Swing components such as JButton inherit from JComponent, which is ultimately
derived from AWT’s Container and Component classes.

Explain the MVC (Model-View-Controller)


Architecture in the Context of Swing. How
does Swing implement the MVC pattern?
Give suitable examples. (10 Marks)
MVC (Model-View-Controller) Architecture

MVC is a software design pattern that separates an application into three components: Model,
View, and Controller. This separation improves maintainability, flexibility, and reusability of
code.

Components of MVC

1. Model

●​ Manages and stores the application’s data.


●​ Maintains the state information of the component.

2. View
●​ Responsible for displaying data to the user.
●​ Handles the visual representation of the application.

3. Controller

●​ Handles user input and interactions.


●​ Updates the model and controls application behavior.

Traditional MVC Diagram


User
|
v
Controller
|
v
Model
|
v
View
|
v
User

MVC in Swing

In Swing, a visual component consists of three aspects:

●​ The way the component looks on the screen.


●​ The way the component reacts to user actions.
●​ The state information associated with the component.

Swing uses a modified MVC architecture in which the View and Controller are combined
into a single component, while the Model remains separate.

Component = View + Controller


Model = Separate

This simplifies the MVC architecture and provides better flexibility.

Swing Components Using MVC

Swing Component Model Used


JList ListModel

JTable TableModel

JTree TreeModel

Example

JList with ListModel


import [Link].*;

public class MVCDemo {


public static void main(String args[]) {

String data[] = {"Java", "Python", "C++"};

JList<String> list = new JList<>(data);

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


[Link](list);

[Link](300,200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

Explanation:

●​ Model: ListModel stores the list data.


●​ View: JList displays the data.
●​ Controller: JList handles user interactions such as selection.

Advantages of MVC in Swing

1.​ Separation of data and user interface.


2.​ Easy maintenance and modification.
3.​ Improved code reusability.
4.​ Multiple views can use the same model.
5.​ Changes in the model do not affect the UI design.

Conclusion

Swing implements a modified MVC architecture by combining the View and Controller into a
single component while keeping the Model separate. Components such as JList, JTable, and
JTree use ListModel, TableModel, and TreeModelrespectively. This approach provides
flexibility, easier maintenance, and better separation of concerns.

Last-Minute Revision
MVC = Model + View + Controller

Model → Data
View → Display
Controller → User Input

Swing MVC:
(View + Controller) = Component
Model = Separate

Examples:
JList → ListModel
JTable → TableModel
JTree → TreeModel

This is more than sufficient for a full 10-mark university answer.

Describe the Event Handling Mechanism


in Swing. How are ActionListener and
other event listeners implemented in
Swing applications? Provide a relevant
code example. (10 Marks)
Introduction
Event handling is the mechanism by which a Swing application responds to user actions such
as button clicks, mouse movements, and keyboard inputs. Swing uses the Delegation Event
Model for handling events efficiently. In this model, the component generating the event
delegates the processing of the event to a registered listener.

Delegation Event Model


The Delegation Event Model consists of three main components:

1. Event Source

The object that generates an event.

Examples: JButton, JTextField, JCheckBox.

2. Event Object

An object that contains information about the event that occurred.

Examples: ActionEvent, MouseEvent, KeyEvent.

3. Event Listener

An interface that receives and handles events generated by the source. The listener must be
registered with the source.

Event Handling Process


User Action
|
v
Event Source
(JButton)
|
Generates
Event Object
(ActionEvent)
|
Sent To
Event Listener
(ActionListener)
|
actionPerformed()
|
Response

ActionListener in Swing
ActionListener is used to handle action events generated by components such as buttons,
menu items, and text fields.

Steps to Implement ActionListener

1.​ Create the component.


2.​ Register the listener using addActionListener().
3.​ Override the actionPerformed() method.
4.​ Write the code to be executed when the event occurs.

Syntax
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Event handling code
}
});

Common Event Listeners in Swing

Listener Interface Purpose

ActionListener Handles button clicks and menu selections

MouseListener Handles mouse events

KeyListener Handles keyboard events


ItemListener Handles checkbox and radio button events

FocusListener Handles focus gained and lost events

Example Program Using ActionListener


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

public class EventDemo {


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](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

Explanation

●​ JButton acts as the Event Source.


●​ Clicking the button generates an ActionEvent.
●​ The registered ActionListener receives the event.
●​ The actionPerformed() method is executed and displays the message “Button
Clicked”.
Advantages of Event Handling in Swing
1.​ Efficient event processing.
2.​ Separation of event-handling code from GUI components.
3.​ Supports multiple types of user interactions.
4.​ Easy to maintain and extend applications.
5.​ Promotes modular programming.

Conclusion
Swing uses the Delegation Event Model to handle user interactions. It consists of an Event
Source, Event Object, and Event Listener. The ActionListener interface is commonly used to
handle button click events, while listeners such as MouseListener, KeyListener, and
ItemListener handle other user interactions. This mechanism makes Swing applications
interactive and user-friendly.

Quick Revision
Delegation Event Model

Event Source → Generates Event


Event Object → Contains Event Information
Event Listener → Handles Event

ActionListener → Button Click


MouseListener → Mouse Events
KeyListener → Keyboard Events
ItemListener → CheckBox/RadioButton Events

This is a complete university-style 10-mark answer with definition, diagram, listener types,
implementation steps, program, and conclusion.
What is Painting in
Swing? Describe the
use of
paintComponent()
method and explain how custom painting
is done in Swing. (10 Marks)
Introduction
Painting in Swing is the process of drawing graphics and visual elements on the screen. It is
used for rendering custom graphics such as shapes, text, images, charts, and games. Swing
provides the paintComponent() method for performing custom painting on components.

The
paintComponent()
Method
The paintComponent() method is defined in the JComponent class and is used to draw
custom graphics on a Swing component.

Syntax
protected void paintComponent(Graphics g)
{
[Link](g);

// Custom Drawing Code


}

Purpose of

paintComponent()

●​ Performs custom drawing on a component.


●​ Called automatically whenever the component needs to be redrawn.
●​ Uses the Graphics object to draw shapes, text, and images.
●​ [Link](g) clears the component before repainting and prevents
overlapping of drawings.

Custom Painting in Swing


Custom painting is performed using the following steps:

Step 1: Extend a Swing Component

Usually a JPanel is extended.

class MyPanel extends JPanel


{
}

Step 2: Override

paintComponent()
protected void paintComponent(Graphics g)
{
[Link](g);
}
Step 3: Draw Graphics Using the Graphics Object

The Graphics class provides methods for drawing various shapes and text.

Common methods:

[Link](x, y, width, height);


[Link](x, y, width, height);
[Link](x, y, width, height);
[Link](x1, y1, x2, y2);
[Link]("Hello", x, y);

Adding Colors to Graphics


Colors can be applied using the setColor() method.

Syntax
[Link]([Link]);

Examples:

[Link]([Link]);
[Link](50,50,100,50);

[Link]([Link]);
[Link](50,50,100,50);

Here:

●​ fillRect() creates a filled blue rectangle.


●​ drawRect() draws a black border around it.

Common predefined colors:

[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Custom Painting Process
Create JPanel

Override paintComponent()

Get Graphics Object

Set Color (Optional)

Draw Shapes/Text

Display on Screen

Example Program
import [Link].*;
import [Link].*;

class MyPanel extends JPanel {

protected void paintComponent(Graphics g) {

[Link](g);

[Link]([Link]);
[Link](50, 50, 100, 50);

[Link]([Link]);
[Link](50, 50, 100, 50);

[Link]("Hello Swing!", 60, 80);


}
}

public class PaintDemo {

public static void main(String args[]) {

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

[Link](new MyPanel());
[Link](300, 200);
[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);
}
}

Explanation

●​ MyPanel extends JPanel.


●​ paintComponent() is overridden.
●​ [Link](g) clears the panel before drawing.
●​ setColor([Link]) sets the drawing color.
●​ fillRect() creates a filled rectangle.
●​ drawRect() draws the border.
●​ drawString() displays text.
●​ The panel is added to a JFrame and displayed.

Advantages of Custom Painting


1.​ Allows creation of custom graphics and shapes.
2.​ Useful for games, charts, and drawing applications.
3.​ Provides flexibility in GUI design.
4.​ Supports colored and dynamic graphics.
5.​ Enhances the visual appearance of Swing applications.

Conclusion
Painting in Swing is used to render graphics on components. Custom painting is achieved by
extending a component, overriding the paintComponent() method, and using the Graphics
object to draw shapes, text, and colored graphics. The paintComponent() method forms the
foundation of graphical programming in Swing.

Quick Revision
Painting = Drawing graphics on screen
Steps:
1. Extend JPanel
2. Override paintComponent(Graphics g)
3. Use Graphics object

Important Methods:
[Link](g)
setColor()
drawRect()
fillRect()
drawOval()
drawLine()
drawString()

drawRect() → Outline only


fillRect() → Filled rectangle

This version is better for exams because it includes painting theory + paintComponent() +
custom painting steps + color handling using setColor() and fillRect(), which often earns
extra marks when writing descriptive answers.
Write a Java Swing application that uses JLabel and
ImageIcon to display an image and a label. Explain how
these components work. (10 Marks)
Introduction

JLabel is a Swing component used to display text, images, or both. ImageIcon is a class
used to load images that can be displayed by Swing components such as JLabel. These
components are commonly used for displaying static information in a graphical user interface.

JLabel
Definition

JLabel is a Swing component used to display non-editable text, images, or both.

Features

●​ Displays text.
●​ Displays images.
●​ Supports text and image alignment.
●​ Can display both text and image simultaneously.

Example
JLabel label = new JLabel("Hello Swing!");

ImageIcon
Definition

ImageIcon is a Swing class used to load and store images.

Example
ImageIcon icon = new ImageIcon("[Link]");

The image can then be displayed using a JLabel.


Java Program
import [Link].*;

public class LabelImageDemo {

public static void main(String args[]) {

JFrame frame = new JFrame("JLabel and ImageIcon Example");

ImageIcon icon = new ImageIcon("[Link]");

JLabel label = new JLabel("Welcome to Swing", icon, [Link]);

[Link](label);

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

[Link](JFrame.EXIT_ON_CLOSE);
}
}

Explanation of the Program


●​ JFrame creates the main application window.
●​ ImageIcon loads the image file "[Link]".
●​ JLabel displays the text "Welcome to Swing" along with the image.
●​ [Link](label) adds the label to the frame.
●​ setVisible(true) displays the GUI window.

Working of JLabel and ImageIcon


Image File

ImageIcon

JLabel

JFrame

Screen Output

●​ ImageIcon loads the image.


●​ JLabel displays the image and text.
●​ JFrame provides the container for displaying the label.

Advantages
1.​ Easy display of text and images.
2.​ Supports image-text combination.
3.​ Improves GUI appearance.
4.​ Lightweight and platform-independent.
5.​ Easy to customize and align content.

Conclusion
JLabel and ImageIcon are important Swing components used for displaying text and images in
GUI applications. ImageIcon loads the image, while JLabel displays the image, text, or both.
Together they help create user-friendly graphical interfaces.
Compare and Contrast JButton and JToggleButton. Write
a program to demonstrate their usage with event
handling. (10 Marks)
Introduction

JButton and JToggleButton are commonly used Swing button components. Both generate
events when clicked and can be handled using ActionListener. However, their behavior
differs in terms of state management.

JButton
Definition

JButton is a Swing component that represents a clickable button used to perform an action
when pressed.

Example

JButton button = new JButton("Submit");

Characteristics

●​ Executes an action when clicked.


●​ Does not maintain any state.
●​ Returns to its normal appearance after the click.

JToggleButton
Definition

JToggleButton is a Swing component that maintains two states: selected and unselected.

Example

JToggleButton toggle = new JToggleButton("Power");


Characteristics

●​ Maintains ON/OFF state.


●​ Remains selected after clicking.
●​ Useful for switches and settings.

Comparison Between JButton and JToggleButton

Feature JButton JToggleButton

Purpose Performs an action Maintains a state

State Retention No Yes

Selection State Not Available Available

Appearance After Click Returns to normal Remains selected

Example Use Submit, Login Wi-Fi, Dark Mode

Program Demonstrating JButton and JToggleButton


import [Link].*;

import [Link].*;

public class ButtonDemo {


public static void main(String args[]) {

JFrame frame = new JFrame("Button Demo");

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

[Link](50, 50, 120, 30);

JToggleButton toggle = new JToggleButton("OFF");

[Link](50, 100, 120, 30);

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link]("JButton Clicked");

});

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

if([Link]())

[Link]("ON");

else

[Link]("OFF");
}

});

[Link](button);

[Link](toggle);

[Link](null);

[Link](300,250);

[Link](true);

[Link](JFrame.EXIT_ON_CLOSE);

Explanation
●​ JButton generates an ActionEvent when clicked and displays a message.
●​ JToggleButton changes between ON and OFF states.
●​ isSelected() is used to determine whether the toggle button is selected.
●​ Both buttons use ActionListener for event handling.

Advantages
JButton

●​ Simple to use.
●​ Suitable for executing commands.
●​ Widely used in GUI applications.
JToggleButton

●​ Maintains state information.


●​ Useful for enabling/disabling features.
●​ Suitable for switch-like controls.

Conclusion
JButton is used for performing actions, whereas JToggleButton is used for maintaining
ON/OFF states. Both support event handling through ActionListener, but JToggleButton
provides additional functionality by remembering its selected state.

Explain the use of check boxes and radio


buttons in Swing using JCheckBox and
JRadioButton. Create a simple GUI to
show how selection works and how to
group radio buttons. (10 Marks)
Introduction
Swing provides JCheckBox and JRadioButton components for selecting options in a graphical
user interface. A check box allows the user to select multiple options, whereas a radio button
allows only one option to be selected from a group. These components are commonly used in
forms, surveys, and settings panels.

JCheckBox
Definition
JCheckBox is a Swing component that represents an independent option that can be selected
or deselected.

Example

JCheckBox java = new JCheckBox("Java");

Features

●​ Allows multiple selections.


●​ Each check box works independently.
●​ Used for selecting hobbies, skills, interests, etc.

JRadioButton
Definition

JRadioButton is a Swing component used when only one option should be selected from a
set of choices.

Example

JRadioButton male = new JRadioButton("Male");

Features

●​ Allows only one selection within a group.


●​ Used for selecting gender, payment mode, course type, etc.

ButtonGroup
ButtonGroup is used to group radio buttons together so that only one radio button can be
selected at a time.

ButtonGroup group = new ButtonGroup();

[Link](male);
[Link](female);

Without ButtonGroup, multiple radio buttons can be selected simultaneously.

Comparison between JCheckBox and JRadioButton

JCheckBox JRadioButton

Multiple selections allowed Single selection allowed

Independent options Mutually exclusive options

No grouping required Requires ButtonGroup

Example: Hobbies Example: Gender

Program Demonstrating JCheckBox and JRadioButton


import [Link].*;

import [Link].*;

public class SelectionDemo {

public static void main(String args[]) {


JFrame frame = new JFrame("Selection Demo");

JCheckBox java = new JCheckBox("Java");

JCheckBox python = new JCheckBox("Python");

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

[Link](50, 60, 100, 30);

JRadioButton male = new JRadioButton("Male");

JRadioButton female = new JRadioButton("Female");

[Link](50, 110, 100, 30);

[Link](50, 140, 100, 30);

ButtonGroup group = new ButtonGroup();

[Link](male);

[Link](female);

JButton button = new JButton("Show Selection");

[Link](50, 190, 150, 30);

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {


if([Link]())

[Link]("Java Selected");

if([Link]())

[Link]("Python Selected");

if([Link]())

[Link]("Male Selected");

if([Link]())

[Link]("Female Selected");

});

[Link](java);

[Link](python);

[Link](male);

[Link](female);

[Link](button);

[Link](null);

[Link](350,300);

[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);

Explanation
●​ JCheckBox components allow multiple selections such as Java and Python.
●​ JRadioButton components are grouped using ButtonGroup.
●​ ButtonGroup ensures that only one radio button is selected at a time.
●​ isSelected() checks whether a component is selected.
●​ When the button is clicked, the selected options are displayed on the console using
[Link]().

Advantages
1.​ Easy to collect user choices.
2.​ Supports both multiple-choice and single-choice selections.
3.​ Improves user interaction.
4.​ Integrates easily with event handling.
5.​ Provides a user-friendly interface.

Conclusion
JCheckBox is used when multiple options can be selected, whereas JRadioButton is used
when only one option must be selected from a group. The ButtonGroup class is used to group
radio buttons and enforce single selection. These components are widely used in Swing
applications for collecting user input.
Discuss the Functionality of the Four
Commonly Used Buttons in Java Swing.
Illustrate Each with a Suitable Example.
(10 Marks)
Introduction
Buttons are important GUI components in Java Swing that allow users to interact with an
application. Swing provides different types of buttons for different purposes, such as performing
actions, maintaining states, selecting multiple options, and selecting a single option from a
group. The four commonly used buttons are JButton, JToggleButton, JCheckBox, and
JRadioButton.

1. JButton
Functionality

JButton is a push button that performs an action when clicked. It does not maintain any state
after being pressed.

Example

JButton button = new JButton("Submit");

[Link](e ->

[Link]("Button Clicked"));

Uses

●​ Submit button
●​ Login button
●​ Save button
2. JToggleButton
Functionality

JToggleButton maintains two states:

●​ Selected (ON)
●​ Unselected (OFF)

Unlike JButton, it remembers its state after being clicked.

Example

JToggleButton toggle =

new JToggleButton("Power");

[Link](e -> {

if([Link]())

[Link]("ON");

else

[Link]("OFF");

});

Uses

●​ Wi-Fi switch
●​ Bluetooth switch
●​ Dark Mode switch
3. JCheckBox
Functionality

JCheckBox allows users to select or deselect options independently. Multiple check boxes can
be selected simultaneously.

Example

JCheckBox java =

new JCheckBox("Java");

if([Link]())

[Link]("Java Selected");

Uses

●​ Selecting hobbies
●​ Choosing skills
●​ Preference settings

4. JRadioButton
Functionality

JRadioButton allows only one option to be selected from a group. Radio buttons are grouped
using ButtonGroup.

Example

JRadioButton male =

new JRadioButton("Male");
JRadioButton female =

new JRadioButton("Female");

ButtonGroup group =

new ButtonGroup();

[Link](male);

[Link](female);

Uses

●​ Gender selection
●​ Payment method selection
●​ Course type selection

Comparison of Swing Buttons


Button Function

JButton Performs an action when clicked

JToggleButton Maintains ON/OFF state

JCheckBox Allows multiple selections

JRadioButton Allows single selection from a group


Explain the Following Swing Components
with an Example Program:

i) JLabel ii) JTextField iii) JScrollPane iv)


JTable (10 Marks)
Introduction
Swing provides a rich collection of GUI components for developing user-friendly desktop
applications. Among them, JLabel, JTextField, JScrollPane, and JTable are widely used for
displaying information, accepting user input, providing scrolling functionality, and displaying
tabular data respectively.

1. JLabel
Definition

JLabel is a Swing component used to display text, images, or both. It is commonly used for
displaying headings, instructions, and static information.

Example

JLabel label = new JLabel("Welcome to Java Swing");

Features

●​ Displays text and images.


●​ Supports text alignment.
●​ Can display both text and image simultaneously.

2. JTextField
Definition

JTextField is a Swing component used to accept single-line text input from the user. It is
commonly used in forms and data-entry applications.

Example

JTextField textField = new JTextField(20);

Important Methods

[Link]("Hello");

[Link]();

[Link](true);

Features

●​ Accepts single-line input.


●​ Allows text editing.
●​ Supports font customization and event handling.

3. JScrollPane
Definition

JScrollPane is a container that provides horizontal and vertical scroll bars for another
component when its content exceeds the visible area.

Example

JTextArea area = new JTextArea(10,20);

JScrollPane scroll = new JScrollPane(area);

Features

●​ Provides automatic scrolling.


●​ Supports horizontal and vertical scroll bars.
●​ Used with text areas, tables, images, and other large components.
4. JTable
Definition

JTable is a Swing component used to display and manage data in the form of rows and
columns. It is commonly used for displaying database records and tabular information.

Example

String data[][] = {

{"101","Anish"},

{"102","Rahul"}

};

String column[] = {

"ID","Name"

};

JTable table = new JTable(data,column);

Features

●​ Displays data in tabular form.


●​ Supports row and column selection.
●​ Can be connected to database data.
●​ Usually placed inside a JScrollPane.

Combined Example Program


import [Link].*;
public class SwingComponentsDemo {

public static void main(String args[]) {

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

JLabel label = new JLabel("Enter Name:");

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

JTextField textField = new JTextField();

[Link](120,20,120,30);

String data[][] = {

{"101","Anish"},

{"102","Rahul"},

{"103","Karan"}

};

String column[] = {"ID","Name"};

JTable table = new JTable(data,column);

JScrollPane scroll =
new JScrollPane(table);

[Link](20,70,220,100);

[Link](label);

[Link](textField);

[Link](scroll);

[Link](null);

[Link](300,250);

[Link](true);

[Link](

JFrame.EXIT_ON_CLOSE);

Explanation of the Program


●​ JLabel displays the text “Enter Name:”.
●​ JTextField accepts user input.
●​ JTable displays student data in rows and columns.
●​ JScrollPane provides scrolling support for the table.
●​ All components are added to a JFrame and displayed on the screen.
Comparison of Components
Component Purpose

JLabel Displays text or images

JTextField Accepts single-line text input

JScrollPane Provides scrolling capability

JTable Displays data in rows and columns

Conclusion
JLabel, JTextField, JScrollPane, and JTable are important Swing components used for
displaying information, accepting user input, providing scrollable views, and displaying tabular
data. These components help developers create interactive and user-friendly GUI applications.
Build a program to demonstrate icon based button. Each
button displays an icon that represents the flag of a country.
When the button is pressed the name of the country is
displayed

import [Link].*;

import [Link].*;

public class FlagDemo {

public static void main(String args[]) {

JFrame frame = new JFrame("Country Flags");

// Load flag images

ImageIcon indiaIcon =

new ImageIcon("[Link]");

ImageIcon usaIcon =

new ImageIcon("[Link]");

ImageIcon japanIcon =

new ImageIcon("[Link]");
// Create buttons with icons

JButton indiaBtn =

new JButton(indiaIcon);

JButton usaBtn =

new JButton(usaIcon);

JButton japanBtn =

new JButton(japanIcon);

// Position buttons

[Link](20,20,100,60);

[Link](140,20,100,60);

[Link](260,20,100,60);

// Label to display country name

JLabel label =

new JLabel("Click a Flag");

[Link](140,120,200,30);

// Event Handling

[Link](
new ActionListener() {

public void actionPerformed(

ActionEvent e) {

[Link]("India");

});

[Link](

new ActionListener() {

public void actionPerformed(

ActionEvent e) {

[Link]("USA");

});

[Link](

new ActionListener() {

public void actionPerformed(

ActionEvent e) {
[Link]("Japan");

});

[Link](indiaBtn);

[Link](usaBtn);

[Link](japanBtn);

[Link](label);

[Link](null);

[Link](400,250);

[Link](true);

[Link](

JFrame.EXIT_ON_CLOSE);

}
Explain the Event Handling Mechanism
Used by Swing and Develop a Program.
(10 Marks)
Introduction
Event handling is the mechanism through which a Swing application responds to user actions
such as button clicks, mouse movements, and keyboard inputs. Swing uses the Delegation
Event Model for handling events. In this model, the component generating the event delegates
the processing of the event to a listener object.

Delegation Event Model


The Delegation Event Model consists of three main components:

1. Event Source
The object that generates an event.

Examples:

●​ JButton
●​ JTextField
●​ JCheckBox

2. Event Object
An object that contains information about the event that occurred.

Examples:

●​ ActionEvent
●​ MouseEvent
●​ KeyEvent

3. Event Listener
An interface that receives and handles events generated by the source.

Examples:

●​ ActionListener
●​ MouseListener
●​ KeyListener

The listener must be registered with the event source.

Event Handling Process


User Action

Event Source

(JButton)

Generates

Event Object

(ActionEvent)

Sent To

Event Listener
(ActionListener)

actionPerformed()

Response

Common Event Listeners in Swing


Listener Interface Purpose

ActionListener Handles button clicks

MouseListener Handles mouse events

KeyListener Handles keyboard events

ItemListener Handles checkbox and radio button events

FocusListener Handles focus events

Implementing ActionListener
Steps:
1.​ Create the component.
2.​ Register the listener using addActionListener().
3.​ Override the actionPerformed() method.
4.​ Write the code to be executed when the event occurs.

Syntax

[Link](

new ActionListener() {

public void actionPerformed(

ActionEvent e) {

// Event Handling Code

});

Program Demonstrating Event Handling


import [Link].*;

import [Link].*;

public class EventDemo {

public static void main(String args[]) {

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

JButton button =

new JButton("Click Me");

[Link](80,50,120,30);

JLabel label =

new JLabel();

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

[Link](

new ActionListener() {

public void actionPerformed(

ActionEvent e) {

[Link](

"Button Clicked");

});

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

[Link](null);

[Link](300,200);

[Link](true);

[Link](

JFrame.EXIT_ON_CLOSE);

Explanation of the Program


●​ JButton acts as the Event Source.
●​ Clicking the button generates an ActionEvent.
●​ ActionListener receives the event.
●​ The actionPerformed() method is executed automatically.
●​ The label text changes to “Button Clicked” when the button is pressed.

Advantages of Event Handling


1.​ Efficient event processing.
2.​ Separates GUI components from event logic.
3.​ Supports multiple user interactions.
4.​ Easy maintenance and modification.
5.​ Promotes modular programming.
Conclusion
Swing uses the Delegation Event Model to handle user interactions. It consists of an Event
Source, Event Object, and Event Listener. Components such as buttons generate events that
are processed by listeners like ActionListener. This mechanism makes Swing applications
interactive and user-friendly.

You might also like