0% found this document useful (0 votes)
1 views12 pages

Java Module 03

The document provides an overview of Java Swing components, including four types of buttons (JButton, JCheckBox, JRadioButton, JToggleButton) and their functionalities. It explains the MVC architecture, key features of Swing like Pluggable Look and Feel and Lightweight Components, and includes various example programs demonstrating these concepts. Additionally, it discusses event handling in Swing, showcasing how user interactions are managed through event listeners.

Uploaded by

Dhanush Gowda
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)
1 views12 pages

Java Module 03

The document provides an overview of Java Swing components, including four types of buttons (JButton, JCheckBox, JRadioButton, JToggleButton) and their functionalities. It explains the MVC architecture, key features of Swing like Pluggable Look and Feel and Lightweight Components, and includes various example programs demonstrating these concepts. Additionally, it discusses event handling in Swing, showcasing how user interactions are managed through event listeners.

Uploaded by

Dhanush Gowda
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
You are on page 1/ 12

Java module-03

Q.1.a. "Explain the four types of the Swing buttons, with demonstration program."

Four Types of Swing Buttons:

Swing provides different types of buttons, all derived from AbstractButton. The four most
common types are:

1. JButton
o A basic push button that performs an action when clicked.
o Commonly used for submitting forms, triggering events, etc.
2. JCheckBox
o Represents a box that can be checked or unchecked.
o Used when multiple selections are allowed.
3. JRadioButton
o Similar to checkboxes, but grouped using ButtonGroup to allow only one
selection at a time.
o Common in forms with mutually exclusive options (e.g., Gender: Male/Female).
4. JToggleButton
o A two-state button that stays pressed or unpressed.
o Used for on/off switches or toggle states.

Demonstration Program:
java
CopyEdit
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SwingButtonDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Button Types");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// 1. JButton
JButton btn = new JButton("Click Me");
btn.addActionListener(e -> JOptionPane.showMessageDialog(frame,
"JButton Clicked"));

// 2. JCheckBox
JCheckBox checkBox = new JCheckBox("I Agree");

// 3. JRadioButton
JRadioButton option1 = new JRadioButton("Option 1");
JRadioButton option2 = new JRadioButton("Option 2");
ButtonGroup group = new ButtonGroup();
Java module-03
group.add(option1);
group.add(option2);

// 4. JToggleButton
JToggleButton toggle = new JToggleButton("Toggle");

// Add to Frame
frame.add(btn);
frame.add(checkBox);
frame.add(option1);
frame.add(option2);
frame.add(toggle);

frame.setVisible(true);
}
}

Explanation (for Theory):

• All Swing buttons use event listeners to handle clicks.


• They are part of the javax.swing package.
• The AbstractButton class provides core functionality like setting text, icons, and
handling clicks.
• You can also apply custom styles and layouts to enhance the UI.

Q.1.b. "Explain MVC Connector Architecture"

MVC Connector Architecture (5 Marks Answer):

MVC stands for Model-View-Controller. It's a design pattern used in GUI and web applications
to separate logic, UI, and user interaction. The connector architecture defines how these
components interact.

Components of MVC:

1. Model
o Manages the data and business logic.
o Notifies the view when data changes.
2. View
Responsible for displaying the data (UI).
o
It listens to the model and updates when notified.
o
3. Controller
o Handles user input and updates the model accordingly.
o Acts as an intermediary between view and model.
Java module-03

Connector Flow:
sql
CopyEdit
User → Controller → Model → View

• The controller receives input from the view.


• It processes it and updates the model.
• The model then notifies the view to refresh the UI.

Example in Swing:

In Java Swing:

• JTextField (View) displays input


• ActionListener (Controller) handles events
• A separate Student class (Model) stores data

Q.1.c. "What are the two key Swing features? Discuss."

Two Key Features of Swing (5 Marks Answer):

1. Pluggable Look and Feel (PLAF):

• Swing components can change their appearance without changing the code logic.
• Example: You can switch between Windows, Motif, or Metal look and feel at runtime.
• This makes Swing flexible and adaptable across platforms.

2. Lightweight Components:

• Unlike AWT, Swing components do not rely on native OS peers.


• This makes them more portable, faster, and easier to customize.
• Example: JButton, JLabel, etc., are lightweight and drawn by Java itself.

Summary:

These features make Swing platform-independent, visually customizable, and better suited for
modern GUIs compared to AWT.
Java module-03
Q.2.a. Explain the following:
(i) JLabel and ImageIcon
(ii) JTextField

(i) JLabel and ImageIcon:

JLabel:

• A JLabel is a display-only GUI component used to show text, images, or both.


• It does not accept user input.
• Commonly used to label input fields, instructions, or display status.

Important methods:

• setText(String text) – to set or change label text.


• setIcon(Icon icon) – to add an image.

ImageIcon:

• ImageIcon is a class used to load and display images in Swing.


• It is often used with JLabel, JButton, etc.

Example:

java
CopyEdit
JLabel label = new JLabel("Welcome");
ImageIcon icon = new ImageIcon("logo.png");
label.setIcon(icon);

This creates a label with text and an image.

(ii) JTextField:

• JTextField is a Swing component used to accept single-line text input from users.
• It is a key input component in forms and search bars.

Common features:

• Editable by default.
• Can be used with event listeners like ActionListener.
Java module-03
Important methods:

• setText(String s) – sets default or new text.


• getText() – retrieves entered text.
• setColumns(int) – sets visible width in characters.

Example:

java
CopyEdit
JTextField tf = new JTextField(20);
panel.add(tf);
String input = tf.getText();

Summary Table:

Component Purpose Key Use


JLabel Display text/images Static instructions
ImageIcon Load images Attach to JLabel/Button
JTextField Text input from user Forms, search bars

Q.2.b. "Write a program to demonstrate a simple Swing application."

Simple Swing Application Program (10 Marks)

This example demonstrates:

• JFrame
• JLabel
• JButton
• JTextField
• ActionListener

java
CopyEdit
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleSwingApp {


public static void main(String[] args) {
// Create Frame
JFrame frame = new JFrame("Simple Swing App");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
Java module-03
// Create components
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(15);
JButton button = new JButton("Submit");
JLabel outputLabel = new JLabel();

// Add ActionListener to button


button.addActionListener(e -> {
String name = textField.getText();
outputLabel.setText("Hello, " + name + "!");
});

// Add components to frame


frame.add(label);
frame.add(textField);
frame.add(button);
frame.add(outputLabel);

// Display frame
frame.setVisible(true);
}
}

Explanation:

• JFrame is the window.


• JLabel is used to display static text and output.
• JTextField collects user input.
• JButton triggers an action.
• ActionListener handles the button click and displays a greeting.

Q.3.a. "Explain the key features of Swing with a sample program."

Key Features of Java Swing (Theory – 5 Marks):

1. Pluggable Look and Feel (PLAF)


o Swing allows changing the UI theme dynamically (e.g., Metal, Nimbus,
Windows).
o Developers can customize the look and feel of the application easily.
2. Lightweight Components
o Unlike AWT, Swing components are written entirely in Java.
o They don’t rely on platform-native GUI resources (no OS dependency).
3. Rich Set of Components
o Includes JButton, JLabel, JTable, JTree, JTabbedPane, etc.
o Suitable for building complex GUIs.
4. MVC Architecture
Java module-03
o Uses the Model-View-Controller pattern.
o Separation of data (model), interface (view), and logic (controller).
5. Event Handling Support
o Supports powerful event handling using interfaces like ActionListener,
MouseListener, etc.
6. Double Buffering
o Provides smooth UI rendering by reducing flickering during UI updates.

Sample Swing Program (Code – 5 Marks)


java
CopyEdit
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SwingFeatureDemo {


public static void main(String[] args) {
// Create frame
JFrame frame = new JFrame("Swing Features");
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// JLabel
JLabel label = new JLabel("Enter your city:");

// JTextField
JTextField textField = new JTextField(15);

// JButton
JButton button = new JButton("Submit");

// Output Label
JLabel output = new JLabel();

// Button Click Logic


button.addActionListener(e -> {
String city = textField.getText();
output.setText("You live in: " + city);
});

// Add components
frame.add(label);
frame.add(textField);
frame.add(button);
frame.add(output);

// Set Look and Feel (optional)


try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Java module-03
} catch (Exception e) {
System.out.println("Look and feel not set.");
}

frame.setVisible(true);
}
}

Summary (to wrap up):

• Swing is powerful for modern GUI apps.


• It supports custom themes, better performance, reusable components, and cleaner
architecture.
• The example shows basic Swing elements in action with event handling and user
interaction.

Q.3.b. "Write a program to demonstrate icons representing timepieces using JButton and
JToggleButton. When the button is pressed, the name of that timepiece should appear in a
JLabel."

Program to Display Timepiece Icons and Names

This program uses:

• JButton and JToggleButton with icons


• JLabel to display the name of the selected timepiece
• Event handling to detect button presses

You can use any timepiece icons like: clock.png, watch.png, timer.png, alarm.png.

Java Program:
java
CopyEdit
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TimepieceIconDemo {


public static void main(String[] args) {
// Create Frame
JFrame frame = new JFrame("Timepiece Icons");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
Java module-03
// Label to display the selected timepiece
JLabel label = new JLabel("Select a Timepiece");

// Create icons (use your actual image file paths)


ImageIcon clockIcon = new ImageIcon("clock.png");
ImageIcon watchIcon = new ImageIcon("watch.png");

// Create JButton and JToggleButton with icons


JButton btnClock = new JButton(clockIcon);
JToggleButton btnWatch = new JToggleButton(watchIcon);

// Add action listeners


btnClock.addActionListener(e -> label.setText("Clock"));
btnWatch.addActionListener(e -> {
if (btnWatch.isSelected()) {
label.setText("Watch");
} else {
label.setText("Select a Timepiece");
}
});

// Add components to frame


frame.add(btnClock);
frame.add(btnWatch);
frame.add(label);

frame.setVisible(true);
}
}

Q.4.a. Write a program to create a frame for a simple arithmetic calculator using swing
components and layout mangers.

Java Swing Program – Simple Arithmetic Calculator

This program performs basic arithmetic: Addition, Subtraction, Multiplication, Division


It uses:

• JFrame, JTextField, JButton, JLabel


• GridLayout for layout management
• Event handling with ActionListener

Complete Java Code:


java
CopyEdit
import javax.swing.*;
import java.awt.*;
Java module-03
import java.awt.event.*;

public class CalculatorApp {


public static void main(String[] args) {
// Create Frame
JFrame frame = new JFrame("Simple Calculator");
frame.setSize(300, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(5, 2, 10, 10)); // 5 rows, 2 columns

// Create Components
JLabel label1 = new JLabel("Number 1:");
JTextField field1 = new JTextField();

JLabel label2 = new JLabel("Number 2:");


JTextField field2 = new JTextField();

JLabel resultLabel = new JLabel("Result:");


JTextField resultField = new JTextField();
resultField.setEditable(false);

JButton addBtn = new JButton("Add");


JButton subBtn = new JButton("Subtract");
JButton mulBtn = new JButton("Multiply");
JButton divBtn = new JButton("Divide");

// Action Listeners
addBtn.addActionListener(e -> {
double a = Double.parseDouble(field1.getText());
double b = Double.parseDouble(field2.getText());
resultField.setText(String.valueOf(a + b));
});

subBtn.addActionListener(e -> {
double a = Double.parseDouble(field1.getText());
double b = Double.parseDouble(field2.getText());
resultField.setText(String.valueOf(a - b));
});

mulBtn.addActionListener(e -> {
double a = Double.parseDouble(field1.getText());
double b = Double.parseDouble(field2.getText());
resultField.setText(String.valueOf(a * b));
});

divBtn.addActionListener(e -> {
double a = Double.parseDouble(field1.getText());
double b = Double.parseDouble(field2.getText());
if (b != 0)
resultField.setText(String.valueOf(a / b));
else
resultField.setText("Cannot divide by zero");
});

// Add Components to Frame


frame.add(label1); frame.add(field1);
frame.add(label2); frame.add(field2);
Java module-03
frame.add(addBtn); frame.add(subBtn);
frame.add(mulBtn); frame.add(divBtn);
frame.add(resultLabel); frame.add(resultField);

frame.setVisible(true);
}
}

Q.4.b. Explain the event handling mechanism used by Swing with an example program.

Event Handling in Swing (Theory – 5 Marks)

What is Event Handling?

Event handling is how Java programs respond to user actions like:

• Clicking a button
• Typing in a text field
• Selecting from a combo box, etc.

Swing uses Event Delegation Model:

This model has three main components:

1. Event Source – the component that generates the event (e.g., JButton)
2. Event Object – contains information about the event (ActionEvent, MouseEvent, etc.)
3. Event Listener – interface that receives and handles the event (ActionListener,
MouseListener, etc.)

How it works:

• You register a listener to a component using .addXListener() method.


• When an event occurs, the listener's method (like actionPerformed()) is automatically
executed.

Example Program: Button Click Event


java
CopyEdit
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class EventHandlingDemo {


public static void main(String[] args) {
Java module-03
// Create Frame
JFrame frame = new JFrame("Event Handling Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// Create Components
JLabel label = new JLabel("Click the button:");
JButton button = new JButton("Click Me");

// Register ActionListener
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Button was clicked!");
}
});

// Add components
frame.add(label);
frame.add(button);

// Show frame
frame.setVisible(true);
}
}

Explanation:

• JButton is the event source.


• ActionEvent is the event object triggered when the button is clicked.
• ActionListener is the event listener that handles the event.
• The actionPerformed() method defines what happens when the button is clicked.

You might also like