0% found this document useful (0 votes)
6 views

Advance Java Chapter 2 Full Notes - Ur Engineering Friend

Uploaded by

rathodnikil07
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Advance Java Chapter 2 Full Notes - Ur Engineering Friend

Uploaded by

rathodnikil07
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Advance Java Notes

MSBTE Diploma

Chapter 2: Swing

• Swing features
• Swing components
• Buttons
• Advance Swing Components
• MVC architecture

Copyright @ Ur Engineering Friend

Ur Engineering Friend is a leading learning platform for MSBTE diploma. All


the copyrights reserved for our content to UEF EdTech Pvt. Ltd.

Please visit our Youtube Channel for more MSBTE Content. Click here !

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


Swings

Define swing -:

In Java, Swing is a part of Java Foundation Classes (JFC) used to create graphical user
interfaces (GUIs) for Java applications. It provides a rich set of lightweight components like
buttons, text fields, tables, trees, and more that can be used to build interactive desktop
applications.

Key Features of Swing:

1. Lightweight Components: Unlike AWT (Abstract Window Toolkit), which relies on


native OS components, Swing components are platform-independent and rendered by
Java itself.
2. Rich UI Elements: Swing offers a wide range of pre-built components such as
JButton, JLabel, JTextField, JTable, etc.
3. Customizable: Swing components can be easily customized in appearance and
behavior.
4. Event-Driven Programming: Swing uses event listeners to handle actions performed
by the user, such as button clicks.
5. Pluggable Look and Feel: Swing allows changing the appearance of applications to
match the operating system or a custom theme.

Limitations of AWT

AWT (Abstract Window Toolkit) is the original GUI framework in Java. While it provides
basic tools to create graphical user interfaces, it has several limitations that led to the
development of Swing as a more advanced alternative. Some key limitations of AWT are:

1. Heavyweight Components:

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


• AWT components rely on native system resources (i.e., they use platform-specific UI
elements). This means the appearance and behavior of AWT components can vary
across different operating systems.
• Since AWT components map directly to the host system's native components, they are
often referred to as "heavyweight," making them less flexible and harder to customize
compared to Swing's lightweight components.

2. Platform Dependency:

• AWT components depend on the underlying operating system's windowing system,


which can cause inconsistencies in how the user interface looks and behaves on
different platforms (e.g., Windows vs. Linux vs. macOS).
• Because of these platform dependencies, bugs that occur in one OS might not appear
in another, making cross-platform development more challenging.

3. Limited Component Set:

• AWT provides only a basic set of components, such as buttons, checkboxes, and text
fields. It lacks more advanced components like tables, trees, tabbed panes, etc., which
are available in Swing.

4. Poor Event Handling Model:

• AWT originally had a less efficient event-handling mechanism based on inheritance.


The event delegation model was introduced later but was still not as flexible as
Swing’s event handling, which makes working with user events more cumbersome.

5. Lack of Pluggable Look and Feel:

• AWT does not support customizable or pluggable look and feel, meaning the user
interface elements will always look like the default system components. Developers
have little control over how the components look, limiting the aesthetic flexibility of
applications.

6. Performance Issues:

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


• AWT's reliance on native resources can lead to performance bottlenecks, especially
when creating complex UIs. Since native system calls are relatively slow,
heavyweight components might slow down the application.

7. Limited Layout Managers:

• AWT layout managers (such as FlowLayout, BorderLayout, and GridLayout) are less
flexible and harder to use for building complex layouts compared to Swing's layout
managers. This makes designing intuitive user interfaces in AWT more difficult.

8. Threading Issues:

• AWT has threading issues because its components are not thread-safe. Developers
must take care when manipulating components across different threads, which can
lead to synchronization problems if not handled correctly.

9. Outdated Technology:

• AWT is considered an older framework, and Java developers have largely moved to
Swing or JavaFX for more modern, feature-rich GUI development. AWT is now used
mainly for backward compatibility.

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


Swing Components

Swing components are part of the Swing library in Java, which is used to create graphical
user interfaces (GUIs) for desktop applications. These components are lightweight, meaning
they are written entirely in Java and do not depend on the native system's GUI elements,
offering a consistent appearance across platforms. They are also highly customizable,
allowing developers to create modern, interactive interfaces.

Key Swing Components:

1. JFrame:
o Purpose: Represents a window with title bars and borders.
o Usage: It's the main container for other components in a GUI application.
o Example: A window where you can place buttons, labels, and other
components.

JFrame frame = new JFrame("My Swing Window");


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

2. JButton:
o Purpose: A push button that triggers an action when clicked.
o Usage: Commonly used for submitting forms, executing commands, etc.
o Example:

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


frame.add(button);

3. JLabel:
o Purpose: Displays a text string or an image.
o Usage: Used to add non-editable text or images to the GUI.
o Example:

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


JLabel label = new JLabel("Welcome to Swing!");
frame.add(label);

4. JTextField:
o Purpose: A single-line text input field.
o Usage: Allows users to input data such as a name or email.
o Example:

JTextField textField = new JTextField(20); // 20 columns wide


frame.add(textField);

5. JTextArea:
o Purpose: A multi-line area for text input or output.
o Usage: Suitable for longer text inputs, like comments or descriptions.
o Example

JTextArea textArea = new JTextArea(5, 20); // 5 rows, 20 columns


frame.add(textArea);

6. JCheckBox:
o Purpose: A checkbox that can be checked or unchecked.
o Usage: Used for selecting or deselecting options in a form.
o Example:

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


frame.add(checkBox);

7. JRadioButton:
o Purpose: A button that can be selected (along with others in a group), but only
one button in the group can be selected at a time.
o Usage: Ideal for selecting one option from a set, like gender selection
(Male/Female).
o Example:

JRadioButton radioButton1 = new JRadioButton("Option 1");

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


JRadioButton radioButton2 = new JRadioButton("Option 2");
ButtonGroup group = new ButtonGroup();
group.add(radioButton1);
group.add(radioButton2);

8. JComboBox:
o Purpose: A drop-down list that allows users to select one option from a set of
options.
o Usage: Commonly used for choosing options like country, language, etc.
o Example

String[] items = { "Item 1", "Item 2", "Item 3" };


JComboBox<String> comboBox = new JComboBox<>(items);
frame.add(comboBox);

9. JList:
o Purpose: A list of items that allows the user to select one or more items.
o Usage: Useful for presenting a list of selectable items.
o Example

String[] data = { "Item 1", "Item 2", "Item 3" };


JList<String> list = new JList<>(data);
frame.add(list);

10.JTable:
o Purpose: Displays tabular data in rows and columns.
o Usage: Ideal for showing structured data like a database table or spreadsheet.
o Example:

String[][] data = { {"1", "John", "22"}, {"2", "Anna", "25"} };


String[] columns = { "ID", "Name", "Age" };
JTable table = new JTable(data, columns);
frame.add(new JScrollPane(table)); // Table inside a scrollable pane

11.JScrollPane:

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


o Purpose: Provides a scrollable view of a component when content exceeds the
display area.
o Usage: Often used with components like JTextArea, JList, or JTable to enable
scrolling.
o Example:

JTextArea textArea = new JTextArea(10, 30);


JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane);

12.JPanel:
o Purpose: A generic container used to group other components.
o Usage: Useful for organizing layouts within a JFrame. Can hold multiple
components.
o Example:

JPanel panel = new JPanel();


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

13.JMenuBar, JMenu, and JMenuItem:


o Purpose: Used to create a menu bar at the top of a window, containing drop-
down menus and menu items.
o Usage: Commonly used for adding options like "File," "Edit," and "Help"
menus.
o Example

JMenuBar menuBar = new JMenuBar();


JMenu menu = new JMenu("File");
JMenuItem menuItem = new JMenuItem("Open");
menu.add(menuItem);
menuBar.add(menu);
frame.setJMenuBar(menuBar);

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


14. JTree

• Purpose: A Swing component that displays a hierarchical tree structure, allowing


users to navigate through parent-child relationships.
• Usage: Ideal for representing data in a tree-like format, such as file directories,
organizational charts, or menus.

Example of JTree:
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class TreeExample {


public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("JTree Example");

// Root node
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

// Child nodes
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");

// Adding child nodes to root


root.add(child1);
root.add(child2);

// Sub-child node for child1


DefaultMutableTreeNode subChild1 = new DefaultMutableTreeNode("Sub-child 1");
child1.add(subChild1);

// Create the JTree with root node


JTree tree = new JTree(root);

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


// Add tree to scroll pane for scrolling capability
JScrollPane scrollPane = new JScrollPane(tree);

// Add scroll pane to frame


frame.add(scrollPane);

// Set frame properties


frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

15. Swing Progress Bar

• A Swing component that visually represents the progress of a task, showing how
much of the task has been completed.
• Commonly used in scenarios where time-consuming operations like file downloads,
installations, or data processing are taking place.

Types of Progress Bars:

1. Determinate: Shows the specific percentage of the task completed, useful when the
total length of the task is known.
2. Indeterminate: Indicates that the task is running, but the progress cannot be
calculated. It is often used when the duration of the task is uncertain.

Example of JProgressBar (Determinate):


import javax.swing.*;

public class ProgressBarExample {


public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("Progress Bar Example");

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


// Create a JProgressBar with a range from 0 to 100
JProgressBar progressBar = new JProgressBar(0, 100);

// Set initial progress to 0


progressBar.setValue(0);

// Display percentage string on the progress bar


progressBar.setStringPainted(true);

// Add progress bar to the frame


frame.add(progressBar);

// Set frame properties


frame.setSize(400, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

// Simulate progress in a separate thread


for (int i = 0; i <= 100; i++) {
try {
// Pause for 100 milliseconds to simulate time-consuming task
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}

// Update the progress bar value


progressBar.setValue(i);
}
}
}

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


Example of JProgressBar (Indeterminate):
import javax.swing.*;

public class IndeterminateProgressBar {


public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("Indeterminate Progress Bar");

// Create a JProgressBar in indeterminate mode


JProgressBar progressBar = new JProgressBar();
progressBar.setIndeterminate(true);

// Add progress bar to frame


frame.add(progressBar);

// Set frame properties


frame.setSize(400, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

// Simulate a task
try {
Thread.sleep(5000); // Task simulation for 5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}

// Stop indeterminate mode after task completion


progressBar.setIndeterminate(false);
}
}

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


MVC Architecture

The MVC (Model-View-Controller) architecture in Java is a design pattern used to separate


the concerns of an application into three interconnected components: the Model, the View,
and the Controller. This separation allows for a modular structure, enabling easier
management, maintenance, and scalability of applications. It is commonly used in desktop,
web, and mobile applications.

Components of MVC:

1. Model:

o Purpose: Represents the data and the business logic of the application.
o Role: The model is responsible for handling the application's data. It responds
to requests for information and updates its state when instructed by the
controller.
o Characteristics:
▪ Encapsulates the data (e.g., user details, products).

Maharashtra’s No.1 Learning Platform For MSBTE Course Details


▪ Handles data manipulation, such as reading from/writing to a database.
▪ Notifies the view of any changes in the data (usually through observers
or listeners).

2. View:

• Purpose: Represents the user interface and displays the data from the model.
• Role: The view is responsible for rendering the model's data in the user interface. It
gets updated when the model changes, but it does not contain business logic.
• Characteristics:
o Displays data to the user.
o Listens for user inputs like clicks, form submissions, etc.
o Updates itself based on model changes.

3. Controller:

• Purpose: Acts as an intermediary between the Model and View.


• Role: The controller handles user input, manipulates the model, and updates the view.
It listens for user actions, processes them, and instructs the model to update or retrieve
data.
• Characteristics:
o Processes user inputs (e.g., button clicks, form submissions).
o Calls methods in the model to update the data.
o Updates the view with new data from the model.

Maharashtra’s No.1 Learning Platform For MSBTE Course Details

You might also like