Module 3
Module 3
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.
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.
TextField JTextField
Label JLabel
[Link](button);
[Link](300, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
Explanation
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.
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.
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
2. View
● Responsible for displaying data to the user.
● Handles the visual representation of the application.
3. Controller
MVC in Swing
Swing uses a modified MVC architecture in which the View and Controller are combined
into a single component, while the Model remains separate.
JTable TableModel
JTree TreeModel
Example
[Link](300,200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
Explanation:
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
1. Event Source
2. Event Object
3. Event Listener
An interface that receives and handles events generated by the source. The listener must be
registered with the source.
ActionListener in Swing
ActionListener is used to handle action events generated by components such as buttons,
menu items, and text fields.
Syntax
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Event handling code
}
});
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked");
}
});
[Link](button);
[Link](300, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
Explanation
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
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);
Purpose of
paintComponent()
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:
Syntax
[Link]([Link]);
Examples:
[Link]([Link]);
[Link](50,50,100,50);
[Link]([Link]);
[Link](50,50,100,50);
Here:
[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].*;
[Link](g);
[Link]([Link]);
[Link](50, 50, 100, 50);
[Link]([Link]);
[Link](50, 50, 100, 50);
[Link](new MyPanel());
[Link](300, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
Explanation
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()
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
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
Example
ImageIcon icon = new ImageIcon("[Link]");
[Link](label);
[Link](400,300);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}
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
Characteristics
JToggleButton
Definition
JToggleButton is a Swing component that maintains two states: selected and unselected.
Example
import [Link].*;
[Link](new ActionListener() {
[Link]("JButton Clicked");
});
[Link](new ActionListener() {
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
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.
JCheckBox
Definition
JCheckBox is a Swing component that represents an independent option that can be selected
or deselected.
Example
Features
JRadioButton
Definition
JRadioButton is a Swing component used when only one option should be selected from a
set of choices.
Example
Features
ButtonGroup
ButtonGroup is used to group radio buttons together so that only one radio button can be
selected at a time.
[Link](male);
[Link](female);
JCheckBox JRadioButton
import [Link].*;
[Link](male);
[Link](female);
[Link](new ActionListener() {
[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
[Link](e ->
[Link]("Button Clicked"));
Uses
● Submit button
● Login button
● Save button
2. JToggleButton
Functionality
● Selected (ON)
● Unselected (OFF)
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
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
Features
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
Important Methods
[Link]("Hello");
[Link]();
[Link](true);
Features
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
Features
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"
};
Features
[Link](20,20,100,30);
[Link](120,20,120,30);
String data[][] = {
{"101","Anish"},
{"102","Rahul"},
{"103","Karan"}
};
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);
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].*;
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);
JLabel label =
[Link](140,120,200,30);
// Event Handling
[Link](
new ActionListener() {
ActionEvent e) {
[Link]("India");
});
[Link](
new ActionListener() {
ActionEvent e) {
[Link]("USA");
});
[Link](
new ActionListener() {
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.
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
Event Source
(JButton)
Generates
Event Object
(ActionEvent)
Sent To
Event Listener
(ActionListener)
actionPerformed()
Response
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() {
ActionEvent e) {
});
import [Link].*;
JFrame frame =
new JFrame("Event Handling");
JButton button =
[Link](80,50,120,30);
JLabel label =
new JLabel();
[Link](80,100,150,30);
[Link](
new ActionListener() {
ActionEvent e) {
[Link](
"Button Clicked");
});
[Link](button);
[Link](label);
[Link](null);
[Link](300,200);
[Link](true);
[Link](
JFrame.EXIT_ON_CLOSE);