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

Unit 2 (Swing, App, Bean)

Java Swing is an extension of AWT that provides a rich set of lightweight, platform-independent components for building graphical user interfaces. It supports advanced features like drag-and-drop, MVC architecture, and a pluggable look and feel, making it suitable for modern applications. The document also covers key Swing components, their functionalities, and a brief introduction to Java Beans and their development using the Bean Development Kit.

Uploaded by

gagan
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)
10 views13 pages

Unit 2 (Swing, App, Bean)

Java Swing is an extension of AWT that provides a rich set of lightweight, platform-independent components for building graphical user interfaces. It supports advanced features like drag-and-drop, MVC architecture, and a pluggable look and feel, making it suitable for modern applications. The document also covers key Swing components, their functionalities, and a brief introduction to Java Beans and their development using the Bean Development Kit.

Uploaded by

gagan
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

Introduction to Java Swing



Swing is a Java Foundation Classes [JFC] library and an extension of the


Abstract Window Toolkit [AWT]. Java Swing offers much-improved
functionality over AWT, new components, expanded components features,
and excellent event handling with drag-and-drop support.
Introduction of Java Swing
Swing has about four times the number of User Interface [UI] components
as AWT and is part of the standard Java distribution. By today’s application
GUI requirements, AWT is a limited implementation, not quite capable of
providing the components required for developing complex GUIs required
in modern commercial applications. The AWT component set has quite a
few bugs and does take up a lot of system resources when compared to
equivalent Swing resources. Netscape introduced its Internet Foundation
Classes [IFC] library for use with Java. Its Classes became very popular
with programmers creating GUI’s for commercial applications.
 Swing is a Set of API (API- Set of Classes and Interfaces)
 Swing is Provided to Design Graphical User Interfaces
 Swing is an Extension library to the AWT (Abstract Window Toolkit)
 Includes New and improved Components that have been enhancing the
looks and Functionality of GUIs’
 Swing can be used to build (Develop) The Standalone swing GUI Apps
as Servlets and Applets
 It Employs model/view design architecture.
 Swing is more portable and more flexible than AWT, the Swing is built
on top of the AWT.
 Swing is Entirely written in Java.
 Java Swing Components are Platform-independent, and The Swing
Components are lightweight.
 Swing Supports a Pluggable look and feel and Swing provides more
powerful components.
 such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
 Further Swing Follows MVC.
 Before getting into the differences, let us first understand what each
of them is.
 1. AWT
AWT stands for Abstract Window Toolkit. It is a platform-
dependent API to develop GUI (Graphical User Interface) or
window-based applications in Java. It was developed by
heavily Sun Microsystems In 1995. It is heavy-weight in use
because it is generated by the system’s host operating system. It
contains a large number of classes and methods, which are used for
creating and managing GUI.
 2. Swing:
Swing is a lightweight Java graphical user interface (GUI) that is
used to create various applications. Swing has platform-
independent components. It enables the user to create buttons and
scroll bars. Swing includes packages for creating desktop
applications in Java. Swing components are written in Java
language. It is a part of Java Foundation Classes(JFC).
 Difference between AWT and Swing:

S.N
O
AWT Swing

Swing is a part of Java Foundation


Java AWT is an API to develop
1. Classes and is used to create various
GUI applications in Java
applications.

The components of Java AWT are The components of Java Swing are light
2.
heavy weighted. weighted.

Java AWT has comparatively less


Java Swing has more functionality as
3. functionality as compared to
compared to AWT.
Swing.

The execution time of AWT is The execution time of Swing is less than
4.
more than Swing. AWT.

The components of Java AWT are The components of Java Swing are
5.
platform dependent. platform independent.

MVC pattern is not supported by


6. MVC pattern is supported by Swing.
AWT.

AWT provides comparatively less Swing provides more powerful


7.
powerful components. components.

AWT components require java.awt Swing components requires javax.swing


8
package package
S.N
O
AWT Swing

AWT is a thin layer of code on top Swing is much larger swing also has
9
of the operating system. very much richer functionality.

Swing is also called as JFC(java


AWT stands for Abstract windows
10 Foundation classes). It is part of oracle’s
toolkit .
JFC.

Using AWT , you have to


11 Swing has them built in.
implement a lot of things yourself .

1. JApplet (Deprecated)
 A Swing-based applet, subclass of java.applet.Applet.
 GUI is added to the contentPane of the JApplet.
 Uses layout managers like FlowLayout, BorderLayout, etc.

Key Methods:

 init() – called to initialize the applet.


 start() – called after init() or when the applet resumes.
 stop() – called when the applet is paused.

2. JButton
A clickable button that performs an action.

Constructors:
 JButton(String text)
 JButton(Icon icon)
 JButton(String text, Icon icon)

Important Methods:
 addActionListener(ActionListener l)
 setText(String)
 setEnabled(boolean)
 setIcon(Icon)

3. JToggleButton
A button that maintains a selected or deselected state.

Constructors:
 JToggleButton(String text)
 JToggleButton(Icon icon)
 JToggleButton(String text, boolean selected)

Useful Methods:

 isSelected() – returns true if selected.


 setSelected(boolean)
 addItemListener(ItemListener)

4. JCheckBox
Used to allow multiple independent selections.

Constructors:
 JCheckBox(String label)
 JCheckBox(String label, boolean selected)

Important Methods:
 isSelected()
 setSelected(boolean)

5. JRadioButton
Allows only one option selected from a group (use with ButtonGroup).

Constructors:
 JRadioButton(String text)
 JRadioButton(String text, boolean selected)

🔷 6. JComboBox
A drop-down list for selecting one item (can also allow text input if editable).

Constructors:

 JComboBox() – empty combo box.


 JComboBox(E[] items)

Important Methods:
 getSelectedItem()
 setSelectedItem(Object)
 addItem(E item)
 removeItem(Object)
 setEditable(boolean)

7. JTextField
A single-line editable text field.

Constructors:
 JTextField(int columns)
 JTextField(String text)
 JTextField(String text, int columns)

Common Methods:
 getText()
 setText(String)
 setEditable(boolean)

8. JTextArea
Multi-line text area for input/output.

Constructors:
 JTextArea(int rows, int columns)
 JTextArea(String text, int rows, int cols)

Common Methods:
 getText()
 setText(String)
 append(String)
 Often placed inside JScrollPane.

Example UI Putting It All Together:


JFrame frame = new JFrame("Swing Example");
frame.setLayout(new FlowLayout());

JButton button = new JButton("Click");


JCheckBox checkBox = new JCheckBox("Accept");
JRadioButton radio1 = new JRadioButton("Option A");
JRadioButton radio2 = new JRadioButton("Option B");
ButtonGroup group = new ButtonGroup();
group.add(radio1);
group.add(radio2);

JComboBox<String> combo = new JComboBox<>(new String[]{"One", "Two"});


JTextField textField = new JTextField(10);
JTextArea textArea = new JTextArea(5, 20);
frame.add(button);
frame.add(checkBox);
frame.add(radio1);
frame.add(radio2);
frame.add(combo);
frame.add(textField);
frame.add(new JScrollPane(textArea));

frame.setSize(400, 300);
frame.setVisible(true);

Summary Table:

Component Use Case

JButton Simple button, executes action on click

JToggleButton Maintains toggle state

JCheckBox Multiple selection options

JRadioButton Single selection among a group

JComboBox Dropdown list for selection

JTextField Single-line text input

JTextArea Multi-line text input

JApplet Swing-based Applet (deprecated)

1. Icons (ImageIcon)
📌 Definition:

An Icon in Java Swing is an interface that represents a fixed-size picture. The most
commonly used implementation is ImageIcon.

📌 Key Uses:

 Icons can be added to components like JLabel, JButton, JCheckBox, JMenuItem,


etc.
 Used to visually enhance the user interface.

📌 Common Class:
ImageIcon icon = new ImageIcon("path/to/image.png");

📌 Important Notes:

 Icons are not interactive.


 Typically used with text to represent actions visually.

🔷 2. JLabel
📌 Definition:

JLabel is a Swing component used to display a short string or an image (or both). It is non-
editable and used for labeling input fields or showing static information.

📌 Key Features:

 Can display text, image, or both.


 Supports alignment (left, right, center).
 Can use tooltips (setToolTipText()).

📌 Constructors:
 JLabel(String text)
 JLabel(Icon image)
 JLabel(String text, Icon icon, int alignment)

🔷 3. JTabbedPane
📌 Definition:

JTabbedPane is a component that lets the user switch between a group of components by
clicking on a tab with a given title and/or icon.

📌 Key Features:

 Each tab contains a separate panel.


 Tabs can be placed at top, bottom, left, or right.

📌 Constructors:
 JTabbedPane()
 JTabbedPane(int tabPlacement)

📌 Methods:
 addTab(String title, Component component)
 setSelectedIndex(int index)
 getSelectedComponent()
🔷 4. JScrollPane
📌 Definition:

JScrollPane provides a scrollable view of a component, such as JTextArea, JTable, JList,


or JTree.

📌 Key Features:

 Automatically shows scrollbars when content overflows.


 Can be used for both vertical and horizontal scrolling.

📌 Constructor:
 JScrollPane(Component view)

📌 Use Case:

Wrap large components to provide scrolling capabilities.

🔷 5. JList
📌 Definition:

JList is a Swing component that displays a list of items. Users can select one or more items
from the list.

📌 Key Features:

 Can be single or multiple selectable.


 Usually placed in a JScrollPane.

📌 Constructors:
 JList(E[] listData)
 JList(ListModel<E>)

📌 Selection Modes:
 SINGLE_SELECTION
 SINGLE_INTERVAL_SELECTION
 MULTIPLE_INTERVAL_SELECTION

🔷 6. JTree
📌 Definition:

JTree is a component that displays hierarchical data, such as directories and files.

📌 Key Features:

 Data is organized in tree nodes.


 Tree nodes can be expanded or collapsed.

📌 Common Classes:

 DefaultMutableTreeNode – to create tree structure.


 TreeModel – for custom data models.

📌 Use Case:

File explorer, navigation menus, organizational hierarchies.

🔷 7. JTable
📌 Definition:

JTable is used to display and edit regular two-dimensional tables of cells.

📌 Key Features:

 Can define rows and columns.


 Highly customizable.
 Editable or read-only.

📌 Constructor:
 JTable(Object[][] data, Object[] columnNames)

📌 Common Usage:

 With DefaultTableModel for dynamic updates.


 Often used with JScrollPane.

🔚 Summary
Component Description Purpose/Use
Icon Represents an image Used with buttons, labels, etc.
JLabel Displays non-editable text or images Static text, labels
JTabbedPane Provides tabbed interface Tab navigation between views
JScrollPane Adds scrollbars to components Scrollable containers
JList Displays a list of selectable items Multiple/single item selection
JTree Shows hierarchical tree structure File trees, menus
JTable Displays tabular data Data grids, editable cells

📘 Introduction to Java Beans


🔸 What is a Java Bean?

A Java Bean is a reusable software component that can be visually manipulated in builder
tools. It follows a set of design conventions that make it easy to use in GUI-based
development environments.

🔸 JavaBeans are:

 Java classes that encapsulate multiple objects into a single object (the bean).
 Serializable (can be saved to disk and restored).
 Easily manipulated in visual editors (like NetBeans, Eclipse GUI builder).

🔸 JavaBean Requirements:

1. Public no-argument constructor


2. Serializable (implements java.io.Serializable)
3. Getter and setter methods for private properties (follow naming convention)

✅ Advantages of Java Beans


Feature Description
🔁 Reusability JavaBeans can be reused in different applications and environments.
Data is hidden using private fields and accessed via getter/setter
🔐 Encapsulation
methods.
🔧 Customizability Beans support customization via property editors.
📦 Portable JavaBeans are platform-independent (Java).
📊 Visual manipulation Easily used in GUI builders like BDK, NetBeans, etc.
🔄 Interoperability Can communicate with other beans/components using events.

🔍 Introspection in Java Beans


🔸 What is Introspection?
Introspection is the process by which a builder tool analyzes a bean to discover its
properties, events, and methods.

🔸 How It Works:

 Uses Java Reflection API (Class and Method classes).


 Can detect:
o Properties (via getX() / setX() methods)
o Methods (all public methods)
o Events (like addXListener())

🔸 Example:
public class StudentBean {
private String name;

public String getName() { return name; }


public void setName(String name) { this.name = name; }
}

The builder will recognize "name" as a property.

🛠 BDK – Bean Development Kit


🔸 What is BDK?

BDK (Bean Development Kit) is a tool provided by Sun Microsystems (now Oracle) that
allows developers to create, test, and manipulate Java Beans in a visual environment.

🔸 Features:

 A visual layout editor.


 Allows drag-and-drop of beans onto the workspace.
 Supports connecting events between beans.
 Provides introspection to inspect bean properties.

🔸 Main Components:

1. ToolBox – Lists available beans.


2. BeanBox – Workspace to place and configure beans.
3. PropertySheet – Shows properties of selected bean.
4. Event Monitor – Monitors bean events.

🌐 Developing a Home Page Using Applet & Swing


🔸 Objective:

Create a simple home page using Swing components inside an applet.

🔸 Required Components:

 JApplet (to host the applet)


 JLabel, JButton, JTextField (for layout)
 JTabbedPane or JPanel (for organizing sections)

🔸 Conceptual Design:

 Header with a welcome message


 Navigation buttons (Home, About, Contact)
 Central panel for content
 Footer or additional info

🔸 Example Code Outline:


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

public class HomePageApplet extends JApplet {


public void init() {
try {
SwingUtilities.invokeAndWait(this::createGUI);
} catch (Exception e) {
System.out.println("GUI creation failed: " + e);
}
}

private void createGUI() {


setLayout(new BorderLayout());

// Header
JLabel header = new JLabel("Welcome to My Home Page",
JLabel.CENTER);
header.setFont(new Font("Arial", Font.BOLD, 18));
add(header, BorderLayout.NORTH);

// Navigation buttons
JPanel navPanel = new JPanel();
navPanel.add(new JButton("Home"));
navPanel.add(new JButton("About"));
navPanel.add(new JButton("Contact"));
add(navPanel, BorderLayout.SOUTH);

// Center content
JTextArea content = new JTextArea("This is a sample home page using
Swing inside an Applet.");
add(new JScrollPane(content), BorderLayout.CENTER);
}
}

⚠️Note: Modern Java versions deprecate applets. This is valid only in Java 8 or older.
🔚 Summary
Topic Description
Reusable components with encapsulated data, following specific
JavaBeans
conventions
Advantages Reusability, encapsulation, GUI support, platform-independence
Introspection Enables GUI tools to analyze beans’ properties, methods, events
BDK Visual tool to create/test JavaBeans, with drag-drop support
Applet & Swing Home Simple GUI with layout, navigation, and content using Swing
Page inside an applet

You might also like