0% found this document useful (0 votes)
22 views64 pages

All AJP Unit ShortCut Theory

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)
22 views64 pages

All AJP Unit ShortCut Theory

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/ 64

Unit 1 AWT (Abstract Window Toolkit)

Short Cut -Study


Abstract Window Toolkit (AWT)
Definition:
AWT is a Java library for building platform-independent graphical user interfaces
(GUIs). It provides basic components like buttons, text fields, and layout
managers for designing windowed applications. AWT is part of Java’s standard
library and uses the native GUI features of the operating system.
Features:
1. Platform Independence: Creates GUIs that run seamlessly across
different operating systems.
2. Lightweight Components: Uses native OS resources for rendering GUI
elements, ensuring efficiency.
3. Event Handling: Provides mechanisms for handling user interactions like
clicks, keystrokes, and mouse movements.

1.1 Components of AWT


Component
• A basic building block of a GUI, such as a button, label, or text field.
• All AWT components inherit from the Component class, which provides
common properties like size and position.
• Examples include Button, Label, and TextField.
Container
• A special type of Component that can hold and organize other components.
• Containers simplify layout management and allow nesting of GUI
elements.
• Examples include Panel, Frame, and Window.

1
Window
• A top-level container without borders or a menu bar, used for displaying
standalone GUI components.
• Windows are not embedded within other containers and serve as
independent application windows.
• Examples include Dialog and Frame.
Frame
• A top-level container with a title bar, borders, and controls like minimize,
maximize, and close.
• Frames are resizable and are typically the main window of an application.
• Example: Frame or its Swing equivalent, JFrame.
Panel
• A lightweight container used to group and organize related components
within a GUI.
• Panels don’t have borders, titles, or menus, making them ideal for dividing
complex GUIs into sections.
• Example: Panel, often used with layout managers like FlowLayout.

1.2 Creating Windowed Programs and Applets


Windowed Program
• A program that uses GUI windows to interact with the user instead of a
command-line interface.
• Typically uses AWT classes like Frame or Panel to create and display
windows.
• Example: Creating a resizable frame using the Frame class:
• Frame frame = new Frame("My Window");
• frame.setSize(300, 200);
• frame.setVisible(true);

2
Applet
• A small GUI-based Java program designed to run within a web browser
(now deprecated).
• Applets inherit from the Applet class and override methods like init() and
paint().
• Example: A simple applet displaying "Hello World":
• import java.applet.Applet;
• import java.awt.Graphics;

• public class MyApplet extends Applet {


• public void paint(Graphics g) {
• g.drawString("Hello World", 50, 50);
• }
• }

AWT Controls (Detailed List with All Constructors, Methods, and


Constants)
1. Label
• Definition:
A Label is a non-editable text component used to display short, static text
like instructions, titles, or output.
• Constructors:
1. Label() – Creates an empty label.
2. Label(String text) – Creates a label with the specified text.
3. Label(String text, int alignment) – Creates a label with text and
specified alignment (Label.LEFT, Label.CENTER, Label.RIGHT).
• Methods:
o setText(String text) – Updates the label text.

3
o getText() – Retrieves the current text of the label.
o setAlignment(int alignment) – Sets the alignment (LEFT, CENTER,
RIGHT).
o getAlignment() – Returns the current alignment.
• Constants:
o Label.LEFT – Aligns text to the left.
o Label.CENTER – Centers text.
o Label.RIGHT – Aligns text to the right.

2. Button
• Definition:
A Button is a clickable control that performs an action when clicked.
• Constructors:
1. Button() – Creates a button with no label.
2. Button(String label) – Creates a button with the specified label.
• Methods:
o setLabel(String label) – Sets the button text.
o getLabel() – Retrieves the current label of the button.
o addActionListener(ActionListener listener) – Registers an action
listener to handle button click events.
o removeActionListener(ActionListener listener) – Removes a
registered action listener.
• Constants: None.

3. Checkbox
• Definition:
A Checkbox is a GUI control that lets the user select or deselect an option.
• Constructors:
1. Checkbox() – Creates a checkbox with no label.

4
2. Checkbox(String label) – Creates a checkbox with the specified
label.
3. Checkbox(String label, boolean state) – Creates a checkbox with an
initial selection state.
4. Checkbox(String label, CheckboxGroup group, boolean state) –
Creates a checkbox that belongs to a group, enabling radio button
behavior.
• Methods:
o setState(boolean state) – Sets the selection state of the checkbox.
o getState() – Checks if the checkbox is selected.
o setLabel(String label) – Updates the checkbox label.
o getLabel() – Retrieves the current label of the checkbox.
• Constants: None.

4. CheckboxGroup
• Definition:
A CheckboxGroup manages a group of checkboxes, ensuring only one
checkbox can be selected at a time (radio button behavior).
• Constructors:
1. CheckboxGroup() – Creates an empty checkbox group.
• Methods:
o getSelectedCheckbox() – Returns the currently selected checkbox in
the group.
o setSelectedCheckbox(Checkbox checkbox) – Sets a specific
checkbox as selected.
• Constants: None.

5. Scrollbar
• Definition:
A Scrollbar is a slider that allows navigation through a range of values,
either horizontally or vertically.
5
• Constructors:
1. Scrollbar() – Creates a default vertical scrollbar.
2. Scrollbar(int orientation) – Creates a scrollbar with the specified
orientation (Scrollbar.HORIZONTAL or Scrollbar.VERTICAL).
3. Scrollbar(int orientation, int value, int visible, int min, int max) –
Creates a scrollbar with the specified orientation, initial value,
visible size, and range.
• Methods:
o setValue(int value) – Updates the scrollbars current value.
o getValue() – Retrieves the scrollbars current value.
o setMinimum(int min) – Sets the minimum value of the scrollbar.
o setMaximum(int max) – Sets the maximum value of the scrollbar.
o addAdjustmentListener(AdjustmentListener listener) – Registers a
listener to handle scrollbar adjustments.
o removeAdjustmentListener(AdjustmentListener listener) –
Removes a registered adjustment listener.
• Constants:
o Scrollbar.HORIZONTAL – Horizontal orientation.
o Scrollbar.VERTICAL – Vertical orientation.

6. TextField
• Definition:
A TextField is a single-line text control for user input or text display.
• Constructors:
1. TextField() – Creates an empty text field.
2. TextField(String text) – Creates a text field with initial content.
3. TextField(int columns) – Creates a text field with specified column
width.
4. TextField(String text, int columns) – Creates a text field with content
and column width.

6
• Methods:
o setText(String text) – Sets the text content.
o getText() – Retrieves the current text.
o setEditable(boolean editable) – Enables or disables editing.
o isEditable() – Checks if editing is enabled.
o addActionListener(ActionListener listener) – Registers an action
listener to handle Enter key events.
• Constants: None.

7. TextArea
• Definition:
A TextArea is a multi-line text component for input or text display.
• Constructors:
1. TextArea() – Creates an empty text area.
2. TextArea(String text) – Creates a text area with initial content.
3. TextArea(int rows, int columns) – Creates a text area with specified
rows and columns.
4. TextArea(String text, int rows, int columns) – Creates a text area
with content, rows, and columns.
• Methods:
o setText(String text) – Updates the text area content.
o getText() – Retrieves the current content.
o append(String text) – Appends text to the existing content.
o replaceRange(String str, int start, int end) – Replaces a portion of
text with the specified string.
• Constants: None.

7
8. Choice
• Definition:
A Choice is a dropdown list that allows users to select one item from a set
of options.
• Constructors:
1. Choice() – Creates an empty dropdown menu.
• Methods:
o add(String item) – Adds an item to the menu.
o getSelectedItem() – Retrieves the selected item.
o getSelectedIndex() – Retrieves the index of the selected item.
• Constants: None.

Layout
1. FlowLayout
• Definition:
1. FlowLayout is a layout manager that arranges components in a left-
to-right flow.
2. If there is no more space on the current row, it moves to the next row,
creating a new line.
3. This layout is often used for simple interfaces, like forms or toolbars,
where components are evenly distributed.
• Constructors:
o FlowLayout() – Creates a layout with centered alignment and default
gaps.
o FlowLayout(int alignment) – Creates a layout with specified
alignment (e.g., FlowLayout.LEFT).
o FlowLayout(int alignment, int hgap, int vgap) – Creates a layout
with specified alignment and horizontal/vertical gaps.
• Methods:
o setAlignment(int alignment) – Specifies alignment (LEFT,
CENTER, or RIGHT).

8
o getAlignment() – Returns the current alignment.
o setHgap(int hgap) – Sets the horizontal spacing between
components.
o setVgap(int vgap) – Sets the vertical spacing between rows.
• Constants:
o FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT
• Example:
• setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20));
• add(new Button("Button 1"));
• add(new Button("Button 2"));

2. BorderLayout
• Definition:
1. BorderLayout divides the container into five regions: NORTH,
SOUTH, EAST, WEST, and CENTER.
2. Each region can hold one component, and the CENTER region
expands to occupy the remaining space.
3. This layout is useful for designing window-based interfaces, like
web browsers, with distinct regions for navigation, content, and
status bars.
• Constructors:
o BorderLayout() – Creates a layout with default horizontal and
vertical gaps of zero.
o BorderLayout(int hgap, int vgap) – Creates a layout with specified
gaps between regions.
• Methods:
o setHgap(int hgap) – Sets the horizontal spacing between
components.
o setVgap(int vgap) – Sets the vertical spacing between components.
• Constants:

9
o BorderLayout.NORTH,
o BorderLayout.SOUTH,
o BorderLayout.EAST,
o BorderLayout.WEST,
o BorderLayout.CENTER
• Example:
• setLayout(new BorderLayout(10, 10));
• add(new Button("North"),
• BorderLayout.NORTH);
• add(new Button("Center"),
• BorderLayout.CENTER);

3. GridLayout
• Definition:
1. GridLayout organizes components into a grid of equal-sized cells.
2. Each cell can hold one component, and the components are stretched
to fill the available space.
3. This layout is ideal for applications that require a structured, uniform
layout, like calculators or dashboards.
• Constructors:
o GridLayout() – Creates a layout with a single row and column.
o GridLayout(int rows, int cols) – Creates a grid with the specified
number of rows and columns.
o GridLayout(int rows, int cols, int hgap, int vgap) – Creates a grid
with specified horizontal and vertical gaps.
• Methods:
o setRows(int rows) – Sets the number of rows.
o setColumns(int cols) – Sets the number of columns.
o setHgap(int hgap) – Sets the horizontal gap between components.
10
o setVgap(int vgap) – Sets the vertical gap between components.
• Example:
• setLayout(new GridLayout(2, 3, 5, 5));
• add(new Button("1"));
• add(new Button("2"));
• add(new Button("3"));
• add(new Button("4"));

4. CardLayout
• Definition:
1. CardLayout allows you to stack components on top of each other,
where only one component is visible at a time.
2. You can navigate between components by flipping "cards," using
commands like next, previous, or first.
3. This layout is particularly useful for wizard-like interfaces, tabbed
panels, or transitions between different sections of an app.
• Constructors:
o CardLayout() – Creates a layout with no gaps.
o CardLayout(int hgap, int vgap) – Creates a layout with specified
horizontal and vertical gaps.
• Methods:
o show(Container parent, String name) – Displays the card with the
specified name.
o next(Container parent) – Shows the next card.
o previous(Container parent) – Shows the previous card.
o first(Container parent) – Displays the first card.
o last(Container parent) – Displays the last card.
• Example:
• CardLayout cardLayout = new CardLayout();

11
• setLayout(cardLayout);
• add(new Button("Card 1"), "Card1");
• add(new Button("Card 2"), "Card2");
• cardLayout.show(this, "Card2");

5. GridBagLayout
• Definition:
1. GridBagLayout is a flexible and complex layout manager that
arranges components in a grid.
2. Unlike GridLayout, components can span multiple rows or columns,
providing greater flexibility for precise control over the layout.
3. It is most useful in creating complex user interfaces where
components need to be positioned dynamically.
• Constructor:
o GridBagLayout() – Creates an instance of GridBagLayout.
• Methods:
o Works with GridBagConstraints to control component positioning.
o setConstraints(Component comp, GridBagConstraints constraints) –
Sets constraints for a component.
• GridBagConstraints Constants:
o GridBagConstraints.RELATIVE,
GridBagConstraints.REMAINDER,
GridBagConstraints.HORIZONTAL,
GridBagConstraints.VERTICAL.
• Example:
• GridBagLayout gridBagLayout = new GridBagLayout();
• setLayout(gridBagLayout);
• GridBagConstraints gbc = new GridBagConstraints();
• gbc.gridx = 0; gbc.gridy = 0;
• add(new Button("Button"), gbc);
12
6. MenuBar and Menus
• Definition:
1. A MenuBar is a container that holds Menu objects, which in turn
contain MenuItem objects.
2. MenuItem represents individual actions or commands within the
menu, and Menu is typically used to organize these items logically.
3. This is essential in creating menus for applications, allowing users
to interact with options such as "File," "Edit," or "View."
• Constructors:
o MenuBar() – Creates a blank menu bar.
o Menu(String label) – Creates a menu with a label.
o MenuItem(String label) – Creates a menu item with a label.
• Methods:
o add(Menu menu) – Adds a menu to the menu bar.
o add(MenuItem item) – Adds an item to a menu.
• Example:
• MenuBar menuBar = new MenuBar();
• Menu menu = new Menu("File");
• menu.add(new MenuItem("Open"));
• menu.add(new MenuItem("Save"));
• menuBar.add(menu);

7. Dialog
• Definition:
1. A Dialog is a pop-up window used for user interaction, often for
alerts, confirmations, or data input.
2. It can be modal (blocks interaction with other windows) or non-
modal (does not block interaction with other windows).

13
3. Dialogs are useful for showing messages, requesting input, or
confirming actions without taking up much screen space.
• Constructors:
o Dialog(Frame parent) – Creates a non-modal dialog.
o Dialog(Frame parent, String title) – Creates a non-modal dialog with
a title.
o Dialog(Frame parent, String title, boolean modal) – Creates a modal
dialog with a title.
• Methods:
o setVisible(boolean visible) – Controls the visibility of the dialog.
o setTitle(String title) – Sets the title of the dialog.
• Example:
• Dialog dialog = new Dialog(new Frame(), "Info", true);
• dialog.setSize(200, 100);
• dialog.setVisible(true);

8. FileDialog
• Definition:
1. A FileDialog is a window that allows users to select files for opening
or saving.
2. It can be customized for either loading (FileDialog.LOAD) or saving
(FileDialog.SAVE) files, helping users browse the file system.
3. This dialog makes file operations easier by providing an integrated UI for
file selection rather than requiring manual input.
• Constructors:
o FileDialog(Frame parent) – Creates a file dialog for loading files.
o FileDialog(Frame parent, String title) – Creates a file dialog with a
title.
o FileDialog(Frame parent, String title, int mode) – Creates a file
dialog for loading or saving files.

14
• Methods:
o setFile(String file) – Sets a default file name.
o getFile() – Returns the selected file name.
o setDirectory(String dir) – Sets the default directory.
o getDirectory() – Returns the selected directory.
• Constants:
o FileDialog.LOAD, FileDialog.SAVE
• Example:
• FileDialog fileDialog = new FileDialog(new Frame(), "Open File",
FileDialog.LOAD);
• fileDialog.setVisible(true);
• String file = fileDialog.getFile();

15
Unit 1 :Swing
Introduction to Swing
What is Swing?
Swing is a part of Java’s Java Foundation Classes (JFC), providing a rich set of
GUI components to build desktop applications. Swing is platform-independent,
lightweight, and provides advanced features like pluggable look-and-feel, event-
driven programming, and rich component customizations.
Features of Swing:
1. Lightweight: Swing components are not dependent on native OS; they are
written entirely in Java.
2. Pluggable Look-and-Feel: Swing allows changing the appearance of
components dynamically.
3. Rich Set of Components: Includes advanced GUI controls like tables, trees,
tabbed panes, sliders, and more.
4. Customizable Components: Developers can modify or extend existing
Swing components.
5. Event-Driven: Follows the delegation-based event-handling mechanism.
Difference AWT and Swing

16
2.2 Swing Components
1. JApplet
• Definition:
JApplet is a Swing-based applet container used to build applet GUIs with
advanced Swing features. It extends Applet and supports components like
menus, panels, and toolbars.
• Constructors:
o JApplet() – Creates an empty JApplet instance.
• Methods:
o init() – Initializes the applet components.
o start() – Starts the applet lifecycle.
o stop() – Stops the applet lifecycle.
o destroy() – Cleans up resources used by the applet.
o getContentPane() – Returns the content pane where components are
added.
o setContentPane(Container c) – Replaces the content pane.
o setJMenuBar(JMenuBar menuBar) – Adds a menu bar to the applet.
• Constants: None.

2. Icons and Labels (JLabel)


Icons
• Definition:
Icons are images used to decorate or enhance GUI components like buttons
or labels.
JLabel
• Definition:
A JLabel is a display area for a short string of text or an image, often used
for instructions or headers in GUIs.
• Constructors:
o JLabel() – Creates an empty label.

17
o JLabel(String text) – Creates a label with the specified text.
o JLabel(Icon icon) – Creates a label displaying an icon.
o JLabel(String text, Icon icon, int horizontalAlignment) – Creates a
label with text, an icon, and alignment.
• Methods:
o setText(String text) – Sets the labels text.
o getText() – Retrieves the text of the label.
o setIcon(Icon icon) – Sets an icon on the label.
o getIcon() – Returns the current icon.
o setHorizontalAlignment(int alignment) – Sets horizontal alignment
(LEFT, CENTER, RIGHT).
o setVerticalAlignment(int alignment) – Sets vertical alignment (TOP,
CENTER, BOTTOM).
• Constants:
o SwingConstants.LEFT,
o SwingConstants.RIGHT,
o SwingConstants.CENTER
o SwingConstants.TOP,
o SwingConstants.BOTTOM

3. JTextField
• Definition:
JTextField is a lightweight single-line text entry component used for input
or displaying text.
• Constructors:
o JTextField() – Creates a blank text field.
o JTextField(String text) – Creates a text field initialized with text.
o JTextField(int columns) – Creates a text field with a specified width
in columns.

18
o JTextField(String text, int columns) – Creates a text field with text
and width.
• Methods:
o setText(String text) – Updates the field content.
o getText() – Retrieves the text in the field.
o setColumns(int columns) – Sets the number of columns (width).
o getColumns() – Retrieves the number of columns.
o setEditable(boolean editable) – Enables/disables user editing.
o isEditable() – Checks if the text field is editable.
o addActionListener(ActionListener listener) – Registers a listener for
action events.
• Constants: None.

4. JComboBox
• Definition:
JComboBox is a dropdown list that allows users to select one item from a
set of choices.
• Constructors:
o JComboBox() – Creates an empty combo box.
o JComboBox(E[] items) – Creates a combo box pre-populated with
items.
• Methods:
o addItem(E item) – Adds an item to the combo box.
o getItemAt(int index) – Retrieves the item at a specified index.
o getItemCount() – Returns the number of items in the combo box.
o setSelectedItem(Object item) – Sets the currently selected item.
o getSelectedItem() – Returns the selected item.
o addActionListener(ActionListener listener) – Registers an action
listener for selection changes.

19
• Constants: None.

2.3 Buttons
1. JButton
• Definition:
JButton is a push button that triggers an action event when clicked.
• Constructors:
o JButton() – Creates an empty button.
o JButton(String text) – Creates a button with a text label.
o JButton(Icon icon) – Creates a button with an icon.
• Methods:
o setText(String text) – Sets the buttons label text.
o getText() – Returns the buttons text.
o setIcon(Icon icon) – Sets an icon for the button.
o addActionListener(ActionListener listener) – Registers an action
listener for click events.

2. JCheckBox
• Definition:
JCheckBox is a button that can be toggled on or off to represent a selection
state.
• Constructors:
o JCheckBox() – Creates an unselected checkbox.
o JCheckBox(String text) – Creates a checkbox with a label.
o JCheckBox(String text, boolean selected) – Creates a checkbox with
a label and initial state.
• Methods:
o setSelected(boolean state) – Updates the selection state.
o isSelected() – Returns whether the checkbox is selected.

20
3. JRadioButton
• Definition:
JRadioButton is a single-selection button used in groups, where only one
button in the group can be selected.
• Constructors:
o JRadioButton() – Creates an unselected radio button.
o JRadioButton(String text) – Creates a radio button with a label.
o JRadioButton(String text, boolean selected) – Creates a button with
a label and initial state.
• Methods:
o setSelected(boolean selected) – Updates the selection state.
o isSelected() – Checks if the button is selected.

21
2.4 Advanced Swing Components

1. JTabbedPane
• Definition:
JTabbedPane is a container that allows you to organize multiple panels
within tabs, so that each tab displays different content. It allows users to
switch between different views in the same space.
• Constructors:
o JTabbedPane() – Creates an empty JTabbedPane with default tab
layout.
o JTabbedPane(int tabPlacement) – Creates a JTabbedPane with
specified tab placement (JTabbedPane.TOP,
JTabbedPane.BOTTOM, JTabbedPane.LEFT,
JTabbedPane.RIGHT).
• Methods:
o addTab(String title, Component component) – Adds a tab with the
given title and component.
o setTabComponentAt(int index, Component component) – Sets a
custom component for the tab at the specified index.
o getSelectedIndex() – Returns the index of the currently selected tab.
o setSelectedIndex(int index) – Sets the selected tab based on its
index.
o removeTabAt(int index) – Removes a tab at the specified index.
• Constants:
o JTabbedPane.TOP
o JTabbedPane.BOTTOM
o JTabbedPane.LEFT
o JTabbedPane.RIGHT
• Example:
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", new JLabel("This is Tab 1"));
22
tabbedPane.addTab("Tab 2", new JLabel("This is Tab 2"));
frame.add(tabbedPane);

2. JScrollPane
• Definition:
JScrollPane provides a scrollable view for large content areas like text
areas, tables, or images. It automatically adds vertical and horizontal scroll
bars if the content overflows.
• Constructors:
o JScrollPane(Component view) – Creates a scroll pane for the
specified view component.
o JScrollPane(int vsbPolicy, int hsbPolicy) – Creates a scroll pane with
specified policies for vertical and horizontal scroll bars
(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS,
etc.).
• Methods:
o setViewportView(Component view) – Sets the view component
inside the scroll pane.
o getViewport() – Returns the viewport, which is the area that displays
the content.
o setVerticalScrollBarPolicy(int policy) – Sets the vertical scrollbar
policy.
o setHorizontalScrollBarPolicy(int policy) – Sets the horizontal
scrollbar policy.
• Constants:
o ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
o ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS
o ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDE
D
o ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS

23
• Example:
JTextArea textArea = new JTextArea(10, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane);

3. JTree
• Definition:
JTree is used to display hierarchical data in a tree-like structure, where each
node can have child nodes. Its commonly used to represent file systems or
organization structures.
• Constructors:
o JTree() – Creates an empty JTree.
o JTree(TreeNode root) – Creates a JTree with a specified root node.
o JTree(TreeModel model) – Creates a JTree with a custom tree
model.
o JTree(Object[] value) – Creates a JTree with the specified data array
as nodes.
• Methods:
o setSelectionRow(int row) – Selects a specific row in the tree.
o getSelectionPath() – Returns the path of the currently selected node.
o setRootVisible(boolean visible) – Sets whether the root node is
visible.
o expandPath(TreePath path) – Expands the tree to show the path.
• Constants: None.
• Example:
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode child = new DefaultMutableTreeNode("Child");
root.add(child);
JTree tree = new JTree(root);

24
• frame.add(new JScrollPane(tree));

4. JTable
• Definition:
JTable is used for displaying and editing tabular data in rows and columns.
Its commonly used for data grids where each cell can hold text or editable
values.
• Constructors:
o JTable() – Creates an empty table.
o JTable(Object[][] rowData, Object[] columnNames) – Creates a
table with specified row data and column names.
o JTable(TableModel model) – Creates a table with a custom table
model.
• Methods:
o setModel(TableModel model) – Sets a custom model to the table.
o getSelectedRow() – Returns the index of the selected row.
o setRowSelectionInterval(int index0, int index1) – Sets the selection
range for rows.
o getValueAt(int row, int column) – Retrieves the value at a specific
row and column.
o setValueAt(Object value, int row, int column) – Sets a new value at
a specific row and column.
• Constants: None.
• Example:
String[][] data = {{"John", "25"}, {"Jane", "30"}};
String[] columns = {"Name", "Age"};
JTable table = new JTable(data, columns);
frame.add(new JScrollPane(table));

25
5. JProgressBar
• Definition:
JProgressBar visually represents the progress of a task or process by filling
up with color as the task progresses.
• Constructors:
o JProgressBar() – Creates an empty progress bar.
o JProgressBar(int min, int max) – Creates a progress bar with a
minimum and maximum value.
o JProgressBar(int orientation) – Creates a progress bar with a
specified orientation (SwingConstants.HORIZONTAL or
SwingConstants.VERTICAL).
• Methods:
o setValue(int value) – Sets the current progress value.
o getValue() – Returns the current value of the progress bar.
o setMaximum(int max) – Sets the maximum value of the progress
bar.
o setMinimum(int min) – Sets the minimum value of the progress bar.
o setString(String string) – Sets the string to be displayed above the
progress bar.
• Constants:
o SwingConstants.HORIZONTAL
o SwingConstants.VERTICAL
• Example:
JProgressBar progressBar = new JProgressBar(0, 100);
progressBar.setValue(50);
frame.add(progressBar);

26
6. Tool Tips
• Definition:
Tool tips display additional information when the user hovers over
components. They help provide hints or descriptions about a UI element.
• Methods:
o setToolTipText(String text) – Sets the tooltip text that will appear
when the user hovers over a component.
o getToolTipText() – Retrieves the tooltip text for the component.
• Example:
• JButton button = new JButton("Click Me");
• button.setToolTipText("Click this button to perform an action");
• frame.add(button);

MVC Architecture in Short

MVC stands for Model-View-Controller, a design pattern used to separate


concerns in software development. It divides the application into three
components:
1. Model
o Definition: Represents the data and business logic. It handles data
operations like retrieving, updating, and validating.
o Example: A Book object with attributes like title, author, and
methods for managing book data.
2. View
o Definition: Displays the data from the Model to the user. It listens
for updates and refreshes the UI when the data changes.
o Example: A GUI table that shows book details.
3. Controller
o Definition: Handles user input and updates the Model and View
accordingly. It acts as the mediator between Model and View.

27
o Example: A button click to add a new book triggers the Controller,
which updates the Model and then refreshes the View.

How MVC Works Together


1. The View captures user input (e.g., a button click).
2. The Controller processes the input and updates the Model.
3. The Model updates its data and notifies the View.
4. The View updates the UI based on the new data from the Model.

Advantages of MVC
• Separation of Concerns: Distinct responsibilities for each component,
leading to cleaner code.
• Maintainability: Each component can be modified independently.
• Reusability: Views can be updated without affecting the Model or
Controller.

28
Unit 3 :Event Handling
The Delegation Event Model
Definition:
The Delegation Event Model is a design pattern used in Java for handling events.
In this model, event sources (e.g., buttons, text fields) generate events, and
event listeners (objects implementing listener interfaces) handle those events.
The event source "delegates" the responsibility of handling the event to the
listeners.
• Event Sources: Objects that trigger events (e.g., buttons, checkboxes).
• Event Listeners: Interfaces with methods to process specific events (e.g.,
ActionListener, MouseListener).

Event Classes
1. ActionEvent Class
Definition:
An ActionEvent represents a user action, typically a button click or menu item
selection.
• Constructors:
o ActionEvent(Object source, int id, String command)
Creates an ActionEvent with the source, event ID, and action
command.
• Methods:
o getActionCommand()
Returns the action command string associated with this event.
o getSource()
Returns the source of the event.
o getID()
Returns the event ID (ACTION_PERFORMED).
o toString()
Returns a string representation of this ActionEvent.
• Constants:
o ActionEvent.ACTION_PERFORMED

29
o ActionEvent.ACTION_FIRST
o ActionEvent.ACTION_LAST
Example:
ActionEvent event = new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, "submit");
System.out.println(event.getActionCommand()); // Outputs: submit

2. ItemEvent Class
Definition:
An ItemEvent is triggered when an item is selected or deselected (e.g., checkbox,
radio button).
• Constructors:
o ItemEvent(Object source, int id, Item item)
Creates an ItemEvent with the source, event ID, and item that
triggered the event.
• Methods:
o getItem()
Returns the item associated with the event.
o getStateChange()
Returns the state change (SELECTED or DESELECTED).
o toString()
Returns a string representation of the ItemEvent.
• Constants:
o ItemEvent.SELECTED
o ItemEvent.DESELECTED
Example:
ItemEvent event = new ItemEvent(checkbox,
ItemEvent.ITEM_STATE_CHANGED, checkbox.getItem());
System.out.println(event.getStateChange()); // Outputs: SELECTED (1)

30
3. KeyEvent Class
Definition:
A KeyEvent represents a keyboard interaction (key pressed, released, or typed).
• Constructors:
o KeyEvent(Component source, int id, long when, int modifiers, int
keyCode,char keyChar)
Creates a KeyEvent with the source, event ID, modifiers, key code,
and key character.
• Methods:
o getKeyCode()
Returns the key code (e.g., VK_ENTER, VK_A).
o getKeyChar()
Returns the character corresponding to the key.
o getModifiers()
Returns the modifier keys (Shift, Ctrl, Alt).
o isActionKey()
Returns true if the key is an action key (e.g., Enter, Backspace).
o toString()
Returns a string representation of the KeyEvent.
• Constants:
o KeyEvent.VK_ENTER
o KeyEvent.VK_ESCAPE
o KeyEvent.VK_F1
o KeyEvent.KEY_PRESSED
o KeyEvent.KEY_RELEASED
o KeyEvent.KEY_TYPED
Example:
KeyEvent event = new KeyEvent(source, KeyEvent.KEY_PRESSED,
System.currentTimeMillis(), 0, KeyEvent.VK_A, a);
System.out.println(event.getKeyChar()); // Outputs: a

31
4. MouseEvent Class
Definition:
A MouseEvent represents actions like mouse clicks, movements, and dragging.
• Constructors:
o MouseEvent(Component source, int id, long when, int modifiers, int
x, int y, int clickCount, boolean popupTrigger)
Creates a MouseEvent with the source, event ID, position, click
count, and popup trigger flag.
• Methods:
o getX()
Returns the x-coordinate of the mouse event.
o getY()
Returns the y-coordinate of the mouse event.
o getClickCount()
Returns the number of clicks.
o getButton()
Returns the mouse button pressed (BUTTON1, BUTTON2,
BUTTON3).
o getModifiers()
Returns modifier keys pressed (Shift, Ctrl, Alt).
o getSource()
Returns the source of the event (component that triggered the event).
o getXOnScreen()
Returns the x-coordinate on the screen.
o getYOnScreen()
Returns the y-coordinate on the screen.
• Constants:
o MouseEvent.BUTTON1
o MouseEvent.BUTTON2
o MouseEvent.BUTTON3
o MouseEvent.MOUSE_PRESSED

32
o MouseEvent.MOUSE_RELEASED
o MouseEvent.MOUSE_CLICKED
o MouseEvent.MOUSE_MOVED
o MouseEvent.MOUSE_DRAGGED
Example:
MouseEvent event = new MouseEvent(component,
MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), 0, 200, 150, 1,
false);
System.out.println(event.getX()); // Outputs: 200

5. TextEvent Class
Definition:
A TextEvent is triggered when a change occurs in the text of a text component
like JTextField or JTextArea.
• Constructors:
o TextEvent(Object source, int id)
Creates a TextEvent with the source and event ID.
• Methods:
o getText()
Returns the updated text after the event.
o getSource()
Returns the source of the event (the text component).
o toString()
Returns a string representation of the TextEvent.
• Constants:
o TextEvent.TEXT_VALUE_CHANGED
Example:
TextEvent event = new TextEvent(textField,
TextEvent.TEXT_VALUE_CHANGED);
System.out.println(event.getText()); // Outputs the updated text.

33
6. WindowEvent Class
Definition:
A WindowEvent represents events triggered by window actions (e.g., opening,
closing, activating).
• Constructors:
o WindowEvent(Window source, int id)
Creates a WindowEvent with the source window and event ID.
• Methods:
o getWindow()
Returns the window that triggered the event.
o getID()
Returns the event ID (e.g., WINDOW_CLOSING).
o getSource()
Returns the source of the event (the window).
o toString()
Returns a string representation of the WindowEvent.
• Constants:
o WindowEvent.WINDOW_OPENED
o WindowEvent.WINDOW_CLOSING
o WindowEvent.WINDOW_CLOSED
o WindowEvent.WINDOW_ICONIFIED
o WindowEvent.WINDOW_DEICONIFIED
o WindowEvent.WINDOW_ACTIVATED
o WindowEvent.WINDOW_DEACTIVATED
Example:
WindowEvent event = new WindowEvent(window,
WindowEvent.WINDOW_CLOSING);
System.out.println(event.getWindow()); // Outputs: the window that was closed.

34
Adapter Classes
Definition:
Adapter classes in Java are used to provide default implementations for listener
interfaces. They allow you to implement only the methods you need by extending
an abstract class, instead of implementing all the methods of an interface.
Usage:
• Adapter classes simplify event handling by providing empty method
implementations. You only need to override the methods youre interested
in.
• Common adapter classes include MouseAdapter, KeyAdapter, and
WindowAdapter.
Syntax:
class MyMouseListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked!");
}
}
Example:
import java.awt.event.;

public class MouseExample {


public static void main(String[] args) {
Frame frame = new Frame("Adapter Example");
frame.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked!");
}
});

35
frame.setSize(300, 200);
frame.setVisible(true);
}
}
In this example, the MouseAdapter is used to handle mouse clicks without
requiring the implementation of all methods in the MouseListener interface.

Inner Classes
Definition:
An inner class is a class defined within another class. It can access the outer classs
members (fields and methods), even if they are private. Inner classes are often
used for handling events.
Usage:
• Inner classes can be useful for grouping classes that logically belong
together, and they allow access to the outer classs private members.
• There are different types of inner classes: non-static, static, anonymous,
and local.
Syntax:
class Outer {
private String outerField = "Outer";

class Inner {
public void display() {
System.out.println(outerField);
}
}
}
Example:
public class OuterClass {

36
private String outerMessage = "Hello from Outer Class!";

class InnerClass {
public void displayMessage() {
System.out.println(outerMessage); // Accessing outer classs private field
}
}

public static void main(String[] args) {


OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.displayMessage();
}
}

Event Interfaces
1. ActionListener Interface
Definition:
Handles action events like button clicks or menu selections.

Method:
- `void actionPerformed(ActionEvent e)`
Invoked when an action event occurs (e.g., button click).

Syntax:
public class MyActionListener implements ActionListener {

37
public void actionPerformed(ActionEvent e) {
System.out.println("Action performed!");
}
}

2. ItemListener Interface
Definition:
Handles item events like checkbox selection or deselection.
Method:
- `void itemStateChanged(ItemEvent e)`
Invoked when the state of an item (e.g., checkbox) changes.

Syntax:
public class MyItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
System.out.println("Item state changed!");
}
}
3. KeyListener Interface
Definition:
Handles keyboard events, such as key presses, releases, and typing.
Methods:
- `void keyPressed(KeyEvent e)`
Invoked when a key is pressed.
- `void keyReleased(KeyEvent e)`
Invoked when a key is released.
- `void keyTyped(KeyEvent e)`

38
Invoked when a key is typed.

Syntax:
public class MyKeyListener implements KeyListener {
public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
}
4. MouseListener Interface
Definition:
Handles mouse events such as clicks, presses, and releases.
Methods:
- `void mouseClicked(MouseEvent e)`
Invoked when the mouse is clicked.
- `void mousePressed(MouseEvent e)`
Invoked when a mouse button is pressed.
- `void mouseReleased(MouseEvent e)`
Invoked when a mouse button is released.
- `void mouseEntered(MouseEvent e)`
Invoked when the mouse enters a component.
- `void mouseExited(MouseEvent e)`
Invoked when the mouse exits a component.

Syntax:
public class MyMouseListener implements MouseListener {
public void mouseClicked(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }

39
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
}
5. MouseMotionListener Interface
Definition:
Handles mouse motion events like dragging or moving the mouse.
Methods:
- `void mouseDragged(MouseEvent e)`
Invoked when the mouse is dragged.
- `void mouseMoved(MouseEvent e)`
Invoked when the mouse is moved.
Syntax:
public class MyMouseMotionListener implements MouseMotionListener {
public void mouseDragged(MouseEvent e) { }
public void mouseMoved(MouseEvent e) { }
}

6. TextListener Interface
Definition:
Handles events when the text changes in text components such as `JTextField` or
`JTextArea`.
Method:
- `void textValueChanged(TextEvent e)`
Invoked when the text value changes.
Syntax:
public class MyTextListener implements TextListener {
public void textValueChanged(TextEvent e) { }
40
}
7. WindowListener Interface
Definition:
Handles window events such as opening, closing, activating, or deactivating a
window.
Methods:
- `void windowOpened(WindowEvent e)`
Invoked when a window is opened.
- `void windowClosing(WindowEvent e)`
Invoked when a window is in the process of closing.
- `void windowClosed(WindowEvent e)`
Invoked when a window is closed.
- `void windowIconified(WindowEvent e)`
Invoked when a window is minimized.
- `void windowDeiconified(WindowEvent e)`
Invoked when a window is restored from minimized state.
- `void windowActivated(WindowEvent e)`
Invoked when a window is activated.
- `void windowDeactivated(WindowEvent e)`
Invoked when a window is deactivated.

Syntax:
public class MyWindowListener implements WindowListener {
public void windowOpened(WindowEvent e) { }
public void windowClosing(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowIconified(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { }
41
public void windowActivated(WindowEvent e) { }
public void windowDeactivated(WindowEvent e) { }
}

42
Networking
4.1 Socket Overview
Client/Server Model
• Client: A client is an application that sends requests for services or
resources from a server over a network. It initiates communication with the
server and waits for responses. Common examples of clients are web
browsers, email clients, and chat applications.
o Example: A web browser (client) sends requests to a web server
(server), and the server responds by sending the requested web
pages.
• Server: A server is an application that provides services, listens for
incoming requests from clients, and responds to them. Servers typically run
continuously, waiting for client requests.
o Example: A web server listens on port 80 and responds to HTTP
requests from clients by delivering web pages.
Reserved Sockets
• Reserved sockets refer to the well-known ports (port numbers ranging
from 0 to 1023) which are used by common network services. These ports
are predefined and require elevated privileges (administrator or root) to
use.
• Example: Port 80 is reserved for HTTP traffic, Port 443 is reserved for
HTTPS traffic, and Port 21 is reserved for FTP traffic.
Proxy Servers
• A proxy server acts as an intermediary between the client and the server it
wishes to communicate with. Instead of communicating directly with the
server, the client sends its request to the proxy, which forwards the request
to the destination server, and then returns the servers response to the client.
• Benefits: Proxy servers provide benefits like improving security by hiding
client IP addresses, caching content for faster access, and balancing traffic
loads.
Internet Addressing

43
• IP Address: Every device connected to the internet is assigned a unique
identifier known as the IP address. It comes in two versions: IPv4 (e.g.,
192.168.0.1) and IPv6 (e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334).
• Subnet Mask: Divides an IP address into network and host parts,
determining how devices are grouped in a network.
• DNS (Domain Name System): The DNS system translates human-
readable domain names (like www.example.com) into IP addresses that are
used to route the request to the correct server.

4.2 Java and the Net: The Networking Classes and Interfaces
Java provides robust networking capabilities that allow developers to build both
client and server applications. Here’s an overview of the core networking classes
and interfaces:
1. Socket (Client-side Communication)
• Definition: A Socket in Java is used to create a client that can establish a
connection to a server for communication over TCP (Transmission Control
Protocol).
o Constructor:
o public Socket(String host, int port) throws UnknownHostException,
IOException
 Establishes a connection to the server at the specified host and
port.
o Methods:
 getInputStream(): This method returns an input stream for
reading data from the server. It allows the client to receive
data sent by the server.
 InputStream input = socket.getInputStream();
 getOutputStream(): This method returns an output stream to
send data to the server.
 OutputStream output = socket.getOutputStream();
2. ServerSocket (Server-side Communication)

44
• Definition: A ServerSocket is used by a server to listen for incoming client
connections. It listens on a specific port and accepts client connections
when they attempt to connect.
o Constructor:
o public ServerSocket(int port) throws IOException
 Binds the server socket to a specific port number on which it
will listen for client connections.
o Methods:
 accept(): This method listens for an incoming connection
from a client and accepts the connection, returning a Socket
object that represents the connection to the client.
 Socket clientSocket = serverSocket.accept();
3. URL (Uniform Resource Locator)
• Definition: The URL class is used to represent a URL (Uniform Resource
Locator), which identifies a resource on the internet, such as a web page.
o Constructor:
o public URL(String spec) throws MalformedURLException
 Creates a URL object from the given string, representing the
URL of a web resource.
o Methods:
 getProtocol(): Returns the protocol (e.g., "http", "ftp")
specified in the URL.
 String protocol = url.getProtocol();
 getHost(): Returns the host (e.g., "www.example.com") of the
URL.
 String host = url.getHost();
4. URLConnection (Communication with URL Resources)
• Definition: URLConnection is used to represent a connection to a URL. It
allows reading from and writing to resources on the internet.
o Methods:

45
 getInputStream(): Returns an input stream to read data from
the resource.
 InputStream in = connection.getInputStream();
 getOutputStream(): Returns an output stream to write data
to the resource.
 OutputStream out = connection.getOutputStream();
5. DatagramSocket (UDP Communication)
• Definition: A DatagramSocket is used for communication over the UDP
(User Datagram Protocol), a connectionless and faster alternative to TCP.
o Constructor:
o public DatagramSocket() throws SocketException
o public DatagramSocket(int port) throws SocketException
 Creates a DatagramSocket either on a random available port
or a specified port.
o Methods:
 send(DatagramPacket packet): Sends a datagram packet
over the network.
 socket.send(packet);
 receive(DatagramPacket packet): Receives a datagram
packet.
 socket.receive(packet);
6. DatagramPacket (Packet for UDP Communication)
• Definition: A DatagramPacket holds data sent or received by a
DatagramSocket. It contains the data, its length, and the address and port
of the destination.
o Constructor:
o public DatagramPacket(byte[] buf, int length, InetAddress address,
int port)
 Creates a DatagramPacket to send data to a specified address
and port.
o Methods:
46
 getData(): Returns the data stored in the packet.
 byte[] data = packet.getData();
7. InetAddress (IP Address Handling)
• Definition: The InetAddress class is used to represent an IP address. It
provides methods to retrieve information about the local and remote
addresses.
o Factory Methods:
 getByName(String host): Returns the IP address of the given
host.
 InetAddress address =
InetAddress.getByName("www.google.com");
 getLocalHost(): Returns the local machine’s IP address.
 InetAddress localAddress = InetAddress.getLocalHost();
o Instance Methods:
 getHostName(): Returns the host name of the address.
 String hostName = address.getHostName();
 getHostAddress(): Returns the IP address of the host in string
format.
 String ipAddress = address.getHostAddress();

4.3 TCP/IP Client Sockets: Whois


• Whois Protocol is a simple TCP-based protocol used to query domain
name registration information. You can perform a whois query using a TCP
socket connection to a Whois server.
o Example:
o Socket socket = new Socket("whois.iana.org", 43);
o InputStream in = socket.getInputStream();
o OutputStream out = socket.getOutputStream();
o out.write("example.com\n".getBytes());

47
4.4 URL: Format, The URI Class
• URL Format: A URL is typically structured as:
o protocol://host:port/path?query#fragment
o Example:
https://www.example.com:8080/path/to/resource?name=value
• URI Class: A URI (Uniform Resource Identifier) represents a generic URI
and can handle both URLs and URNs.
o Constructor:
o public URI(String scheme, String authority, String path, String
query, String fragment)
o Methods:
 getScheme(): Returns the scheme part of the URI (e.g.,
"http").
o String scheme = uri.getScheme();
 getHost(): Returns the host of the URI.
o String host = uri.getHost();

4.5 URLConnection: TCP/IP Server Sockets


• URLConnection is used for communication with remote resources
identified by a URL.
o **
Example**: java URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();
• TCP/IP Server Sockets are used by servers to listen for client requests. A
ServerSocket listens for incoming client connections and establishes a
communication channel through Socket objects.

4.6 Datagrams: DatagramPacket, Datagram Server, and Client


• DatagramPacket is a container for data in the UDP protocol. It holds the
data, length, and destination information.

48
• DatagramServer Example:
o A server using a DatagramSocket to receive packets from clients.
o DatagramSocket socket = new DatagramSocket(8080);
o byte[] buffer = new byte[1024];
o DatagramPacket packet = new DatagramPacket(buffer,
buffer.length);
o socket.receive(packet);
• DatagramClient Example:
o A client using a DatagramSocket to send a packet to the server.
o DatagramSocket socket = new DatagramSocket();
o byte[] data = "Hello, Server!".getBytes();
o DatagramPacket packet = new DatagramPacket(data, data.length,
InetAddress.getByName("localhost"), 8080);
o socket.send(packet);

Difference

49
Unit 5: Interacting with Database
5.1 Introduction to JDBC and ODBC
JDBC (Java Database Connectivity):
• JDBC is a Java API (Application Programming Interface) that allows Java
applications to interact with databases. It provides methods to connect to a
database, send queries, retrieve results, and update the database.
• It enables Java programs to work with a variety of databases like MySQL,
Oracle, PostgreSQL, etc., by using SQL queries.
Key Concepts of JDBC:
• Connection: Establishing a connection to the database.
• Statement: Creating and executing SQL queries.
• ResultSet: Storing and accessing the result of a query.
• Transaction Management: Controlling transaction behavior (commit,
rollback).
ODBC (Open Database Connectivity):
• ODBC is a standard API that allows applications to access database
management systems (DBMS) using SQL. It works similarly to JDBC but
is language-independent, supporting several programming languages like
C, C++, and Python.
• Key Difference: JDBC is Java-specific, while ODBC is platform-
independent and can be used with various programming languages.
Key Features of ODBC:
• ODBC drivers allow applications to interact with databases using SQL
queries.
• It acts as a middle layer between the application and the database, enabling
portability across different DBMS systems.

5.2 JDBC Architecture: Two-tier and Three-tier Models


JDBC Architecture:
JDBC architecture provides different models for connecting to databases,
depending on the complexity and scalability of the application.

50
1. Two-tier JDBC Architecture:
o Client-side: In this architecture, the client application directly
communicates with the database.
o Database-side: The database server handles requests, processes
them, and sends back the results.
o Example: A desktop application using JDBC to directly connect to
a database like MySQL or Oracle.
o Flow:
 The client sends SQL queries to the database.
 The database processes the request and returns the result
directly to the client.
Pros:
o Simpler design.
o Fast for small-scale applications.
Cons:
o Direct dependency on the database, which can be a bottleneck.
2. Three-tier JDBC Architecture:
o Client-side: The client sends requests, typically through a web
interface or desktop application.
o Middle-tier (Application Server): An application server (e.g.,
Tomcat, JBoss) acts as an intermediary, executing business logic.
o Database-side: The database stores the data and responds to queries.
o Example: A web application where the client communicates with an
application server, which then interacts with the database.
o Flow:
 The client sends a request to the application server.
 The application server processes business logic, sends a query
to the database, and returns results to the client.
Pros:
o More scalable and modular.

51
o Reduces load on the database by using the application server to
handle processing.
Cons:
o More complex architecture.
o Higher latency due to the additional middle layer.

5.3 Types of JDBC Drivers


JDBC defines four types of drivers based on how they communicate with the
database. These drivers determine the communication model between Java
applications and databases.
1. Type 1 Driver (JDBC-ODBC Bridge Driver):
o Description: This driver uses ODBC (Open Database Connectivity)
to connect Java applications to a database.
o Pros:
 Works with any database that has an ODBC driver.
o Cons:
 Performance is slower due to the extra layer (ODBC).
 Deprecated in recent versions of Java.
2. Type 2 Driver (Native-API Driver):
o Description: This driver uses a native database API to connect Java
applications to the database.
o Example: A MySQL driver that uses the MySQL C API.
o Pros:
 Faster than Type 1 as it avoids ODBC overhead.
o Cons:
 Requires native database libraries to be installed on the client
system.
3. Type 3 Driver (Network Protocol Driver):

52
o Description: This driver communicates with the database server
using a database-independent network protocol, often through a
middleware server.
o Pros:
 No need for native database libraries.
 Can be used for multiple database systems.
o Cons:
 Requires a middleware server, which can introduce additional
complexity and latency.
4. Type 4 Driver (Thin Driver):
o Description: This driver communicates directly with the database
using the databases native protocol, without any middleware.
o Example: The MySQL Connector/J is a Type 4 driver that
communicates directly with the MySQL database.
o Pros:
 High performance and lightweight.
 No need for additional software or middleware.
o Cons:
 Specific to a particular database.

5.4 Driver Interfaces Manager Class


The JDBC API provides several interfaces that define how Java interacts with
databases. Here are the key interfaces and their roles:
Driver Interface:
• Definition: The Driver interface defines the methods needed for a JDBC
driver to communicate with a specific database. A driver class must
implement this interface to be used by Java applications.
• Important Method:
o connect(String url, Properties info): Establishes a connection to
the database using the given URL and connection properties.

53
DriverManager Class:
• Definition: The DriverManager class is responsible for managing a list of
database drivers and establishing a connection to a database.
• Important Methods:
o getConnection(String url): Establishes a connection to the
database using the specified URL.
o registerDriver(Driver driver): Registers a driver with the
DriverManager.
Connection Interface:
• Definition: The Connection interface represents an open connection to a
specific database. It is used to create Statement, PreparedStatement, and
CallableStatement objects.
• Important Methods:
o createStatement(): Creates a Statement object for sending SQL
queries to the database.
o prepareStatement(String sql): Creates a PreparedStatement object
for precompiled SQL queries.
o close(): Closes the database connection.
Statement Interface:
• Definition: The Statement interface represents a SQL statement that can
be executed on the database.
• Important Methods:
o executeQuery(String sql): Executes a SELECT query and returns
a ResultSet object.
o executeUpdate(String sql): Executes an SQL statement that
updates data (INSERT, UPDATE, DELETE).
PreparedStatement Interface:
• Definition: The PreparedStatement interface extends the Statement
interface and allows for precompiled SQL queries that can be executed
multiple times with different parameters.
• Important Methods:

54
o setString(int parameterIndex, String value): Sets a parameter in
the prepared statement.
o executeQuery(): Executes the prepared statement and returns a
ResultSet.
ResultSet Interface:
• Definition: The ResultSet interface represents the result of a SQL query
and allows you to retrieve data from it.
• Important Methods:
o next(): Moves the cursor to the next row in the result set.
o getString(String columnLabel): Retrieves a string value from the
specified column.

5.5 The Essential JDBC Program


A typical JDBC program involves the following steps:
1. Load the JDBC Driver: Load the appropriate driver to connect to the
database.
2. Establish a Connection: Use DriverManager to establish a connection to
the database.
3. Create a Statement: Create a Statement or PreparedStatement object to
send SQL queries.
4. Execute Queries: Execute the SQL queries and retrieve the results.
5. Process the Result: Process the ResultSet to fetch the results of the query.
6. Close the Connection: Close the Connection object to release database
resources.
Basic JDBC Program Example:
import java.sql.*;

public class SimpleJDBC {


public static void main(String[] args) {
// Step 1: Load the driver

55
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 2: Establish a connection
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"root", "password");

// Step 3: Create a statement


Statement stmt = conn.createStatement();

// Step 4: Execute a query


ResultSet rs = stmt.executeQuery("SELECT * FROM employees");

// Step 5: Process the result


while (rs.next()) {
System.out.println("Employee ID: " + rs.getInt("id"));
System.out.println("Employee Name: " + rs.getString("name"));
}

// Step 6: Close the connection


conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

56
Explanation:
• Driver Load: The Class.forName() method loads the JDBC driver.
• Connection Establishment: The DriverManager.getConnection() method
establishes a connection to the database using the
specified URL, username, and password.
• Query Execution: The Statement.executeQuery() method is used to
execute the SQL query and retrieve the result as a ResultSet.
• Result Processing: The ResultSet.next() method moves the cursor through
the result set, and getString() or getInt() is used to retrieve column values.
• Resource Cleanup: The Connection.close() method is called to close the
connection and release database resources.

57
Unit 6: Servlet
6.1 The Life Cycle of a Servlet
The lifecycle of a servlet consists of four stages:
1. Loading the Servlet: The servlet is loaded into memory by the servlet
container (web server).
2. Initialization (init()): The init() method is called once when the servlet is
loaded.
3. Request Handling (service()): The service() method handles the client
request.
4. Destruction (destroy()): The destroy() method is called when the servlet is
destroyed.

6.2 Creating a Simple Servlet: The Servlet API, javax.servlet Package


Servlet API:
The Servlet API provides classes and interfaces to handle requests and responses
in web applications.
Key Classes and Interfaces in javax.servlet Package:
1. Servlet Interface:
o Purpose: All servlets must implement this interface.
o Key Methods:
 init(ServletConfig config): Initializes the servlet.
 service(ServletRequest req, ServletResponse res): Handles
requests and sends responses.
 destroy(): Cleans up before servlet is destroyed.
Syntax:
public interface Servlet {
void init(ServletConfig config);
void service(ServletRequest req, ServletResponse res);
void destroy();

58
}
2. ServletConfig Interface:
o Purpose: Provides configuration information to the servlet.
o Key Method:
 getInitParameter(String name): Returns the servlets
initialization parameter.
Syntax:
public interface ServletConfig {
String getInitParameter(String name);
}
3. ServletContext Interface:
o Purpose: Provides information about the entire web application.
o Key Method:
 getInitParameter(String name): Returns the applications
initialization parameter.
Syntax:
public interface ServletContext {
String getInitParameter(String name);
}
4. ServletRequest Interface:
o Purpose: Represents the clients request.
o Key Method:
 getParameter(String name): Returns the value of the
request parameter.
Syntax:
public interface ServletRequest {
String getParameter(String name);
}

59
5. ServletResponse Interface:
o Purpose: Represents the servers response to the client.
o Key Method:
 getWriter(): Returns the output stream for writing the
response.
Syntax:
public interface ServletResponse {
PrintWriter getWriter();
}
6. GenericServlet Class:
o Purpose: A base class that implements the Servlet interface with
default behavior.
Syntax:
public abstract class GenericServlet implements Servlet {
public void init() { /* Initialization code */ }
public abstract void service(ServletRequest req, ServletResponse res);
public void destroy() { /* Cleanup code */ }
}

6.3 The javax.servlet.http Package


This package extends the javax.servlet package and provides classes and
interfaces specific to handling HTTP requests and responses.
1. HttpServletRequest Interface:
o Purpose: Represents an HTTP request from the client.
o Key Method:
 getParameter(String name): Returns the HTTP request
parameter.
Syntax:
public interface HttpServletRequest extends ServletRequest {
60
String getParameter(String name);
}
2. HttpServletResponse Interface:
o Purpose: Represents an HTTP response to the client.
o Key Method:
 getWriter(): Returns the writer to send response data.
Syntax:
public interface HttpServletResponse extends ServletResponse {
PrintWriter getWriter();
}
3. HttpSession Interface:
o Purpose: Manages the session between the client and server.
o Key Method:
 getAttribute(String name): Returns the value of an attribute
in the session.
Syntax:
public interface HttpSession {
Object getAttribute(String name);
}
4. Cookie Class:
o Purpose: Represents an HTTP cookie, which stores small pieces of
data on the client-side.
o Key Method:
 getName(): Returns the name of the cookie.
Syntax:
public class Cookie {
public String getName();
public void setMaxAge(int seconds);

61
}
5. HttpServlet Class:
o Purpose: A subclass of GenericServlet specifically for handling
HTTP requests.
o Key Methods:
 doGet(): Handles GET requests.
 doPost(): Handles POST requests.
Syntax:
public abstract class HttpServlet extends GenericServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response);
protected void doPost(HttpServletRequest request, HttpServletResponse
response);
}

6.4 Handling HTTP Requests and Responses


Handling HTTP GET Requests:
The doGet() method is called when the client sends an HTTP GET request to the
server.
Syntax:
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Handle GET request
}
Handling HTTP POST Requests:
The doPost() method is called when the client sends an HTTP POST request to
the server.
Syntax:
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
62
// Handle POST request
}

6.5 Cookies and Session Tracking


Cookies:
Cookies store data on the client-side to maintain state across requests.
Setting a Cookie: Syntax:
Cookie cookie = new Cookie("username", "John");
cookie.setMaxAge(3600); // 1 hour
response.addCookie(cookie);
Reading a Cookie: Syntax:
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
response.getWriter().println(cookie.getValue());
}
• }
Session Tracking:
Sessions store data across multiple requests from the same client.
• Creating a Session: Syntax:
• HttpSession session = request.getSession();
• session.setAttribute("user", "John");

6.6 Introduction to JSP (JavaServer Pages)


JSP is a technology used for developing dynamic web pages in Java. JSP allows
embedding Java code directly into HTML.
JSP Syntax:
Declarations: Declare variables or methods.
63
<%! String userName = "Guest"; %>
Scriptlets: Embed Java code into HTML.
<%
out.println("Hello, " + userName);
%>
Expressions: Directly output values.
<%= userName %>

Difference Between get() and post() Method

64

You might also like