0% found this document useful (0 votes)
34 views13 pages

Unit V Swing

The document provides an introduction to Swing, a Java GUI toolkit that includes a hierarchy of components such as JFrame, JButton, and JPanel, allowing developers to create rich desktop applications. It explains key features of Swing, including lightweight components, customizable look and feel, and the MVC architecture, along with examples of common components and their usage. Additionally, it details the structure of Swing components, types of containers, and specific components like JToggleButton and JCheckBox, highlighting their functionalities and practical examples.

Uploaded by

PRIYA
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)
34 views13 pages

Unit V Swing

The document provides an introduction to Swing, a Java GUI toolkit that includes a hierarchy of components such as JFrame, JButton, and JPanel, allowing developers to create rich desktop applications. It explains key features of Swing, including lightweight components, customizable look and feel, and the MVC architecture, along with examples of common components and their usage. Additionally, it details the structure of Swing components, types of containers, and specific components like JToggleButton and JCheckBox, highlighting their functionalities and practical examples.

Uploaded by

PRIYA
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
You are on page 1/ 13

Swing: Introduction to Swing-Hierarchy of swing components.

Containers –-J Frame-J Window – J


Dialog – J Panel – J Button – J toggle Top level containers Button – J Check Box – J Radio Button-J
Label, J Text Field – J Text Area – J List – J Combo Box – J Scroll Pane.

Introduction to Swing (as per Herbert Schildt’s The Java Complete Reference, 7th Ed.)
Swing is a part of Java’s Standard Library that provides a rich set of GUI (Graphical
User Interface) components for building desktop applications. It is included in the Java
Foundation Classes (JFC) and offers more sophisticated components than the older AWT
(Abstract Window Toolkit).
Swing was introduced with Java 2 (JDK 1.2) and allows developers to build platform-
independent, visually rich, and user-interactive applications.

Explanation of Swing in Java


🔹 1. What is Swing?
Swing is a GUI toolkit in Java used to create windows, buttons, scroll bars, menus, and
other interface elements.
🔹 2. Key Features:
 Lightweight Components: Unlike AWT, Swing components are written entirely in
Java and do not rely on native code.
 Pluggable Look and Feel: You can change how components look (Windows, Motif,
Metal, etc.) without affecting the behavior.
 MVC Architecture: Follows the Model-View-Controller design pattern for better
separation of concerns.
 Highly Customizable: You can create custom components or extend existing ones.
 Built on AWT: Uses AWT’s event-handling model but replaces many of its UI
components.
🔹 3. Common Swing Components:
Component Description
JFrame Top-level window
JButton Push button
JLabel Display a text string or image
JTextField Single-line text input
JTextArea Multi-line text area
JCheckBox Checkbox
JRadioButton Radio button
JPanel Container to group components
🔹 4. Basic Example:
import javax.swing.*;

public class HelloSwing {


public static void main(String[] args) {
JFrame frame = new JFrame("My First Swing App");
JLabel label = new JLabel("Hello, Swing!", JLabel.CENTER);
frame.add(label);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Hierarchy of Swing Components (From Herbert Schildt’s Java Complete


Reference)
In Java Swing, the components follow a hierarchical structure rooted in the
java.awt.Component class. The hierarchy reflects how GUI elements are organized, starting
from base classes to more complex Swing components.

Swing Component Hierarchy:


java.lang.Object
└── java.awt.Component
└── java.awt.Container
└── javax.swing.JComponent
├── JLabel
├── JButton
├── JTextField
├── JTextArea
├── JCheckBox
├── JRadioButton
├── JList
├── JTable
├── JTree
├── JPanel
└── JScrollPane
Some top-level containers:
javax.swing.JComponent
└── java.awt.Container
└── javax.swing.JRootPane
├── JFrame
├── JDialog
└── JApplet

🧩 Explanation of Important Classes in the Hierarchy:


🔹 1. Component (from java.awt)
 The base class for all AWT and Swing components that can be displayed on the
screen.
 Provides basic properties like size, visibility, color, etc.
🔹 2. Container
 A special component that can hold other components (e.g., panels, frames).
 Provides layout management and component organization.
🔹 3. JComponent
 The base class for all Swing lightweight components.
 Inherits from Container.
 Adds Swing-specific features like pluggable look and feel, double buffering, tool
tips, etc.
🔹 4. Top-Level Containers
These are used to host the Swing components:
 JFrame – Represents the main window.
 JDialog – Pop-up window/dialog.
 JApplet – For embedding in web browsers (obsolete now).
🔹 5. Basic Swing Components
Component Description
JLabel Displays a text string or image.
JButton Push button used for actions.
JTextField Accepts a single line of input.
JTextArea Accepts multiple lines of input.
JCheckBox Represents a checkbox.
JRadioButton A radio button for exclusive selection.
JList Displays a list of items.
JTable Tabular representation of data.
JPanel Generic container used for grouping.
JScrollPane Adds scrollbars to components.

Visual Representation (Simplified)


JFrame
└── JPanel (optional for layout)
├── JLabel
├── JButton
├── JTextField
└── other components...

Containers in Swing
In Swing, a container is a component that can hold and organize other GUI components
like buttons, labels, and text fields. All containers inherit from the class java.awt.Container,
which itself is a subclass of java.awt.Component.
Herbert Schildt explains containers as the foundation for laying out other components in a
GUI application.

Types of Containers in Swing


Swing defines several container classes, mainly divided into top-level containers and
lightweight containers:

1. Top-Level Containers
These are the starting points of any Swing application. You cannot add components directly
to them—you must add components to their content panes.
Container Description
JFrame A main application window. Most commonly used.
JDialog A pop-up dialog window. Can be modal or modeless.
JApplet A container for applets (now outdated).
➤ Example:
JFrame frame = new JFrame("My Window");
frame.setSize(400, 300);
frame.setVisible(true);

2. Lightweight Containers
These are used inside top-level containers to organize components using layout managers.
Container Description
JPanel Generic lightweight container for grouping components.
JScrollPane Provides scrollbars to view large components.
JTabbedPane Holds multiple panels with tabs.
JSplitPane Splits space between two components.
JLayeredPane Allows components to overlap each other.
➤ Example using JPanel:
JPanel panel = new JPanel();
panel.add(new JButton("Click Me"));

frame.add(panel); // add panel to the frame

Key Concepts (from Herbert Schildt):


 All Swing containers are derived from Container (in AWT), and many are
subclasses of JComponent.
 You must use layout managers to control how components are arranged inside a
container.
 You can nest containers: a JPanel inside a JFrame, a JScrollPane inside a JPanel, and so
on.

Hierarchy Overview (Simplified):


java.lang.Object
└── java.awt.Component
└── java.awt.Container
├── javax.swing.JComponent
│ └── JPanel, JScrollPane, etc.
└── javax.swing.JWindow
├── JFrame
├── JDialog
└── JApplet

Top-Level Containers
In Java Swing, a top-level container is the foundation on which all Swing applications are
built. These containers are the entry point of the GUI, and they are responsible for holding
all other components and containers (like buttons, text fields, panels, etc.).
Herbert Schildt explains that without a top-level container, you cannot create a visible
GUI window in Swing.

Types of Top-Level Containers in Swing


Swing provides three primary top-level containers:
Top-Level
Description
Container
JFrame A standard window used for most Swing applications.
A pop-up window used for short-term interactions (e.g., alerts,
JDialog
confirmations).
Used for applets embedded in a browser (now outdated and rarely
JApplet
used).
Each of these containers automatically contains a JRootPane, which in turn contains:
 A content pane
 A glass pane
 A layered pane
 An optional menu bar

🔷 1. JFrame – Main Window


 Most commonly used.
 Represents a resizable window with a title bar and borders.
 Suitable for desktop applications.
✅ Example:
import javax.swing.*;

public class MyFrame {


public static void main(String[] args) {
JFrame frame = new JFrame("My Application");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

🔶 2. JDialog – Dialog Window


 Used to display modal or modeless pop-up windows.
 Can be used for alerts, confirmations, or custom dialog boxes.
✅ Example:
JDialog dialog = new JDialog(frame, "My Dialog", true);
dialog.setSize(200, 100);
dialog.setVisible(true);
🔸 3. JApplet – Browser-Based Applet (Obsolete)
 Used to create Java programs that run in a web browser.
 Now deprecated in modern Java due to security and browser compatibility issues.
✅ Example:
public class MyApplet extends JApplet {
public void init() {
add(new JLabel("Hello from Applet"));
}
}

📌 Note (from Herbert Schildt’s Book)


 Each top-level container uses a content pane to hold components. So, components
are not added directly to JFrame or JDialog, but to their content pane.
 For example:
frame.getContentPane().add(new JButton("Click Me"));
However, modern Java lets you add directly to the frame, as the default content pane is
automatically managed.

🧠 Key Characteristics of Top-Level Containers


Feature JFrame JDialog JApplet
Has a title bar ✅ ✅ ❌
Can be modal ❌ ✅ ❌
Used for Main windows Pop-up dialogs Browser-based apps (legacy)
Contains RootPane ✅ ✅ ✅

📘 JPanel in Swing
In Java Swing, JPanel is a generic lightweight container used to organize and group other
components in a GUI. According to Herbert Schildt, JPanel is one of the most commonly used
containers and plays a vital role in managing layout and component arrangement.

🔹 Definition and Purpose


 JPanel is a subclass of JComponent.
 It serves as a container for holding and grouping other components like buttons, labels, etc.
 You typically use it when you want to organize components either visually or logically.
 It is not a top-level container, meaning it must be added to another container like a JFrame
or JDialog.

🔑 Constructors (from the book)


JPanel() // Creates a panel with FlowLayout (default)
JPanel(LayoutManager layout) // Creates panel with specified layout

🧱 Key Features of JPanel


Feature Description
Lightweight Fully written in Java (unlike heavyweight AWT components)
Feature Description
Supports various layout managers (FlowLayout, GridLayout, BorderLayout,
Customizable Layout
etc.)
Can Be Nested You can place one JPanel inside another to build complex UIs
Painting Support Can override paintComponent() to perform custom drawing

✅ Simple Example Using JPanel


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

public class PanelExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JPanel Example");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Creating a JPanel with a GridLayout


JPanel panel = new JPanel(new GridLayout(2, 2));

panel.add(new JButton("Button 1"));


panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
panel.add(new JButton("Button 4"));

// Adding panel to the frame


frame.add(panel);
frame.setVisible(true);
}
}
🟢 In this example:
 A JPanel is created with a 2x2 GridLayout.
 Four buttons are added to the panel.
 The panel is added to a JFrame.

🧠 Why Use JPanel? (Schildt’s Insights)


 Modular Design: Break your GUI into manageable sections.
 Reusable: You can reuse panels across different parts of your application.
 Flexible Layout: Perfect for organizing components in different patterns.

JToggleButton - Top-Level Containers


🔹 What is JToggleButton?
JToggleButton is a swing component that represents a two-state button — it can be on or off,
like a switch. Unlike JButton (which is momentary), JToggleButton maintains its selected state
until toggled again.
It extends from:
AbstractButton → JToggleButton
🧱 Key Features (as per Schildt)
Feature Description
Package javax.swing
Type Subclass of AbstractButton
Toggle State Can be either selected (true) or not selected (false)
Use Case Ideal for features like bold/italic toggle, tool selectors, etc.
Event Handling Generates an ActionEvent when toggled
Grouping Can be grouped with other JToggleButtons or JRadioButtons using ButtonGroup

🔹 Top-Level Container Context


To use JToggleButton, it must be placed inside a top-level container like:
 JFrame
 JDialog
 JApplet
As per Schildt’s description, all visible components must be added to a content pane of a
top-level container.

Example: JToggleButton in a JFrame


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

public class ToggleButtonExample {


public static void main(String[] args) {
// Top-level container
JFrame frame = new JFrame("JToggleButton Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// JToggleButton component
JToggleButton toggleButton = new JToggleButton("OFF");

// Action listener to respond to toggle state


toggleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (toggleButton.isSelected()) {
toggleButton.setText("ON");
} else {
toggleButton.setText("OFF");
}
}
});

// Add toggle button to the frame's content pane


frame.add(toggleButton);
frame.setVisible(true);
}
}
🟢 In this example:
 A JToggleButton starts with label “OFF”.
 When clicked, it toggles to “ON” and vice versa.
 It's placed inside a JFrame, which is a top-level container.

🧠 Schildt’s Insights
Herbert Schildt emphasizes:
 Use JToggleButton when state matters (e.g., ON/OFF, BOLD/UNBOLD).
 Combine with ButtonGroup to create mutually exclusive toggles (like radio buttons).
 It is part of the Swing component hierarchy, and should always be used inside a top-
level container for it to be visible and interactive.

🧩 Common Methods of JToggleButton


Method Description
setSelected(true/false) Sets the toggle state
isSelected() Returns whether the button is ON
setText(String) Sets the label text
addActionListener() Responds to toggle events

JCheckBox
🔹 What is JCheckBox?
JCheckBox is a Swing component that represents a check box — a small box that can be
either checked (true) or unchecked (false).
It is part of the javax.swing package and is a subclass of AbstractButton, which means it
behaves like a button but retains a selected state.

Hierarchy (from Schildt)

↳ java.awt.Component
java.lang.Object

↳ java.awt.Container
↳ javax.swing.JComponent
↳ javax.swing.AbstractButton
↳ javax.swing.JToggleButton
↳ javax.swing.JCheckBox
So, a JCheckBox is a specialized type of toggle button that supports two states: checked and
unchecked.

🔑 Constructors
Herbert Schildt highlights the following commonly used constructors:
JCheckBox() // Creates an unchecked check box with no text
JCheckBox(String text) // Creates an unchecked check box with a label
JCheckBox(String text, boolean selected) // Creates with a label and initial state

🧠 Key Features (from the book)


Feature Description
Two-State Checked / Unchecked
Generates Events ItemEvent and ActionEvent when toggled
Flexible Use Can be used alone or in groups
Part of Swing Lightweight and platform-independent

Example: Using JCheckBox in a JFrame


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

public class CheckBoxExample {


public static void main(String[] args) {
JFrame frame = new JFrame("JCheckBox Example");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

JCheckBox checkBox = new JCheckBox("I agree to the terms");

JButton submit = new JButton("Submit");

submit.addActionListener(e -> {
if (checkBox.isSelected()) {
JOptionPane.showMessageDialog(frame, "Thank you for agreeing!");
} else {
JOptionPane.showMessageDialog(frame, "Please agree to continue.");
}
});

frame.add(checkBox);
frame.add(submit);
frame.setVisible(true);
}
}

How It Works
 A JCheckBox is added to a JFrame (a top-level container).
 When the "Submit" button is clicked, it checks whether the box is selected using
isSelected().
 Based on the state, a message is displayed.

Common Methods of JCheckBox


Method Purpose
isSelected() Returns true if the checkbox is selected
setSelected(boolean) Sets the checkbox state
addItemListener() Responds to state changes
Method Purpose
addActionListener() Responds to click events

Components from Swing


1️.JRadioButton
 A JRadioButton is a toggle button that works as part of a mutually exclusive group.
 When grouped using ButtonGroup, only one button in the group can be selected at a
time.
JRadioButton rb1 = new JRadioButton("Male");
JRadioButton rb2 = new JRadioButton("Female");

ButtonGroup group = new ButtonGroup();


group.add(rb1);
group.add(rb2);
✅ Use Case: Gender selection, payment method, etc.

2️.JLabel
 JLabel is a non-editable text component used to display static text or an image.
JLabel label = new JLabel("Username:");
✅ Use Case: Descriptive labels for form fields.

3️⃣ JTextField
 A JTextField is a single-line input field that allows users to enter and edit text.
JTextField textField = new JTextField(20);
✅ Use Case: Name, email, username input, etc.

4️JTextArea
 JTextArea is a multi-line area for displaying or editing plain text.
JTextArea textArea = new JTextArea(5, 20);
✅ Use Case: Comments, address fields, logs, etc.

5️JList
 JList is used to display a list of items, allowing single or multiple selection.
String[] colors = {"Red", "Green", "Blue"};
JList<String> colorList = new JList<>(colors);
✅ Use Case: Selection of multiple options, like hobbies, skills, etc.

6️JComboBox
 A JComboBox is a drop-down list that lets users choose one item from a list.
String[] countries = {"India", "USA", "UK"};
JComboBox<String> comboBox = new JComboBox<>(countries);
✅ Use Case: Country selection, category selection, etc.

7️JScrollPane
 A JScrollPane provides a scrolling view of another component, like a JTextArea, JList, or
even a JPanel.
JTextArea area = new JTextArea(10, 30);
JScrollPane scrollPane = new JScrollPane(area);
✅ Use Case: When the content exceeds the visible area.

Sample Usage – All Components Together


import javax.swing.*;

public class SwingComponentsExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Components");
frame.setSize(400, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);

// JLabel and JTextField


JLabel nameLabel = new JLabel("Name:");
nameLabel.setBounds(20, 20, 100, 25);
JTextField nameField = new JTextField();
nameField.setBounds(120, 20, 200, 25);

// JRadioButton
JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");
male.setBounds(120, 60, 70, 25);
female.setBounds(200, 60, 80, 25);
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(male);
genderGroup.add(female);

// JTextArea inside JScrollPane


JLabel commentLabel = new JLabel("Comments:");
commentLabel.setBounds(20, 100, 100, 25);
JTextArea commentArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(commentArea);
scrollPane.setBounds(120, 100, 200, 100);

// JList
JLabel listLabel = new JLabel("Select Color:");
listLabel.setBounds(20, 220, 100, 25);
String[] colors = {"Red", "Green", "Blue"};
JList<String> colorList = new JList<>(colors);
JScrollPane listScroll = new JScrollPane(colorList);
listScroll.setBounds(120, 220, 100, 60);

// JComboBox
JLabel countryLabel = new JLabel("Country:");
countryLabel.setBounds(20, 300, 100, 25);
JComboBox<String> countryBox = new JComboBox<>(new String[]{"India", "USA", "UK"});
countryBox.setBounds(120, 300, 120, 25);
frame.add(nameLabel);
frame.add(nameField);
frame.add(male);
frame.add(female);
frame.add(commentLabel);
frame.add(scrollPane);
frame.add(listLabel);
frame.add(listScroll);
frame.add(countryLabel);
frame.add(countryBox);

frame.setVisible(true);
}
}

🧠 Summary Table
Component Purpose
JRadioButton Single-choice option in a group
JLabel Display non-editable text
JTextField Single-line text input
JTextArea Multi-line text input
JList List of selectable items
JComboBox Drop-down for single selection
JScrollPane Adds scrollbars to other components

You might also like