0% found this document useful (0 votes)
12 views23 pages

Java Exception Handling & Multithreading Notes

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)
12 views23 pages

Java Exception Handling & Multithreading Notes

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

OBJECT ORIENTED PROGRAMMING

UNIT 3 & UNIT 4 - COMPLETE NOTES

UNIT III: EXCEPTION HANDLING,


MULTITHREADING, GENERICS &
COLLECTIONS
1. EXCEPTION HANDLING
1.1 Introduction to Exception Handling

Exception handling is a fundamental mechanism in Java that allows programs to handle runtime errors
gracefully, preventing crashes and maintaining normal program flow. An exception is a problem that
occurs during program execution, disrupting the normal flow of the application.

When an exception occurs, the Java Virtual Machine (JVM) creates an exception object containing:

Error name
Error description
Program state at the time of error

The runtime system then searches the call stack for an exception handler, starting from the method
where the exception occurred and proceeding backward.

1.2 Types of Exceptions


Java exceptions are divided into two main categories:

Checked Exceptions:

Must be declared in a method's signature using the throws keyword or handled with try-catch
blocks
Compiler enforces explicit handling
Typically related to external resources like file I/O operations
Examples: IOException, FileNotFoundException, SQLException
Represent conditions that a reasonable application should anticipate and recover from

Unchecked Exceptions (Runtime Exceptions):

Do not need to be explicitly declared or caught


Include programming errors and invalid assumptions
Examples: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException
Generally result from bugs in the code

1.3 Try-Catch Blocks

The try-catch block is the fundamental structure for handling exceptions in Java.
Syntax:

try {
// code that might generate an exception
int divideByZero = 5 / 0;
} catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
}

How it works:

Code that might generate an exception is placed inside the try block
When an exception occurs, the rest of the code in the try block is skipped
Control immediately transfers to the appropriate catch block
If no exception occurs, all catch blocks are skipped entirely

1.4 The Finally Block


The finally block executes regardless of whether an exception occurred. This block is used for
cleanup operations such as closing resources or releasing locks.

Example:

try {
int divideByZero = 5 / 0;
} catch (ArithmeticException e) {
[Link]("ArithmeticException => " + [Link]());
} finally {
[Link]("This is the finally block");
}

The finally block provides guaranteed execution, making it ideal for resource cleanup operations that
must run in all scenarios.

1.5 Multiple Catch Clauses

You can specify multiple catch blocks after a single try block to handle different exception types.
Each catch block targets a specific exception type.

Example:

try {
// Code that may throw multiple exception types
} catch (ArithmeticException e) {
// Handle arithmetic errors
} catch (ArrayIndexOutOfBoundsException e) {
// Handle array index errors
} catch (NumberFormatException e) {
// Handle number format errors
}

Multi-catch (Java 7+):

catch (IOException | FileNotFoundException ex) {


[Link](ex);
throw ex;
}

1.6 The Throw Keyword


The throw keyword allows you to explicitly throw an exception at any point in your code.

Example:

class Main {
public static void divideByZero() {
throw new ArithmeticException("Trying to divide by 0");
}

public static void main(String[] args) {


divideByZero();
}
}

This explicitly created exception will propagate up the call stack until caught by an appropriate
exception handler or until the program terminates.

1.7 The Throws Keyword

The throws keyword declares in a method's signature that it may throw certain checked exceptions.
This tells callers they must handle these exceptions.

Example:

import [Link].*;

class Main {
public static void findFile() throws IOException {
File newFile = new File("[Link]");
FileInputStream stream = new FileInputStream(newFile);
}

public static void main(String[] args) {


try {
findFile();
} catch (IOException e) {
[Link](e);
}
}
}

1.8 Nested Try Statements


You can nest try-catch blocks within each other to handle exceptions at different levels of program
execution.

Example:

try {
try {
// Inner try block
int divideByZero = 5 / 0;
} catch (ArithmeticException e) {
[Link]("Inner catch: " + [Link]());
throw e; // Re-throw if needed
}
} catch (ArithmeticException e) {
[Link]("Outer catch: " + [Link]());
}

1.9 Built-in Exceptions in Java


Common Unchecked Exceptions:

ArithmeticException: Arithmetic operations fail (e.g., division by zero)


ArrayIndexOutOfBoundsException: Accessing array element outside bounds
NumberFormatException: String cannot be converted to numeric type
NullPointerException: Attempting to use a null reference
InputMismatchException: Input doesn't match expected format

Common Checked Exceptions:

IOException: I/O operations fail


FileNotFoundException: File cannot be located
SQLException: Database operations fail

1.10 Exception Information Methods

The Throwable class provides methods to access exception details:

getMessage(): Returns the description of the exception


toString(): Returns the exception class name and message
printStackTrace(): Prints the full stack trace showing error location and call chain

1.11 Creating Custom Exception Classes


You can create custom exception classes by extending the Exception class (for checked exceptions) or
RuntimeException class (for unchecked exceptions).

Example:

// Custom checked exception


public class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

// Custom unchecked exception


public class InsufficientBalanceException extends RuntimeException {
public InsufficientBalanceException(String message) {
super(message);
}
}

// Using custom exceptions


public class BankAccount {
private double balance;

public void withdraw(double amount) throws InsufficientBalanceException {


if (amount > balance) {
throw new InsufficientBalanceException("Insufficient funds");
}
balance -= amount;
}
}

// Handling custom exceptions


try {
[Link](5000);
} catch (InsufficientBalanceException e) {
[Link]("Transaction failed: " + [Link]());
}

2. MULTITHREADING
2.1 Introduction to Multithreading

Java multithreading is a powerful feature that allows a program to execute multiple tasks concurrently
within a single application. Instead of running tasks sequentially, multithreaded programs leverage
system resources more efficiently and improve overall performance.

2.2 The Java Thread Model

The Java thread model is built around the concept of lightweight processes that share the same memory
space within a single program. Threads are independent paths of execution, and multiple threads can
work together efficiently because they share the same memory space.

Benefits:

Better utilization of multi-core processors


Keeps applications responsive during long-running operations
Efficient resource sharing

2.3 Thread Life Cycle


A thread in Java goes through several distinct states during its lifetime:

1. New State

Thread is created but hasn't started executing yet


Exists as a Thread object but JVM hasn't begun running its code

2. Runnable State

Thread has been assigned to a task and is ready to run


Thread sets itself for executing the assigned task

3. Running State

Thread is actively executing


Control enters the thread and performs its task

4. Blocked/Waiting State

Thread temporarily pauses execution


Waiting for a resource or condition to be met
5. Terminated State

Thread completes its execution


No longer alive

2.4 Thread Class and Key Methods


start(): Initiates the execution of a thread. Creates a new call stack and runs the thread's task
independently.

run(): Contains the code that the thread will execute. Override this method to define what the thread
should do.

currentThread(): Returns the reference to the currently executing thread object.

isAlive(): Verifies whether a thread is alive or dead.

sleep(milliseconds): Pauses the current thread for a specified number of milliseconds.

join(): The current thread invokes this method on a second thread, causing the current thread to block
until the second thread terminates.

interrupt(): Gracefully requests that a thread stop executing.

setName() / getName(): Sets or retrieves the name of a Thread object.

setPriority(): Sets the priority of the thread (values between 1 and 10).

setDaemon(): Designates the thread as a daemon thread.

2.5 Creating Threads - Extending Thread Class

Example:

class MyThread extends Thread {


public void run() {
[Link]("Thread is running: " + [Link]().getId());
}
}

public class Main {


public static void main(String[] args) {
MyThread thread = new MyThread();
[Link]();
}
}

2.6 Runnable Interface


The Runnable interface provides a way to create threads without extending the Thread class. This
approach is preferred because Java doesn't support multiple inheritance.

Example:

Runnable task = new Runnable() {


public void run() {
[Link]("Thread is running.");
}
};
Thread thread = new Thread(task);
[Link]();

Using Lambda Expressions:

Thread thread = new Thread(() -> {


[Link]("Thread is running.");
});
[Link]();

2.7 Creating Multiple Threads


Example:

class MultithreadingDemo extends Thread {


public void run() {
try {
[Link]("Thread " + [Link]().getId() + " is runn
} catch (Exception e) {
[Link]("Exception is caught");
}
}
}

public class Multithread {


public static void main(String[] args) {
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object = new MultithreadingDemo();
[Link]();
}
}
}

2.8 Synchronization

When multiple threads access shared data or resources, synchronization is essential to prevent
interference and ensure correct results. Without proper control, threads might corrupt data or produce
unpredictable behavior.

Synchronized Methods:

synchronized void criticalSection() {


// Only one thread can execute this at a time
}

Synchronized Blocks:

synchronized (object) {
// Critical section
}

2.9 Inter-Thread Communication


The wait() and notify() mechanisms allow threads to communicate and coordinate their activities.

Example:

Thread worker = new Thread(() -> {


[Link]("Working...");
try {
[Link](3000);
} catch (InterruptedException e) {
[Link]().interrupt();
[Link]();
}
[Link]("Work complete.");
});

[Link]();

try {
[Link](); // Main thread waits for worker to finish
[Link]("Main thread resumes.");
} catch (InterruptedException e) {
[Link]();
}

2.10 Deadlock
Deadlock Causes:

Circular wait conditions where Thread A holds Resource 1 and waits for Resource 2, while
Thread B holds Resource 2 and waits for Resource 1
Multiple synchronized blocks accessed in different orders by different threads
Improper use of wait() and notify()

Deadlock Prevention:

Lock Ordering: Always acquire locks in the same order across all threads
Timeout Mechanisms: Use methods that allow threads to timeout
Resource Allocation: Minimize the number of locks held simultaneously
Avoid Nested Locks: Reduce the complexity of lock hierarchies

Example - Proper Lock Ordering:

// Thread A
synchronized (resource1) {
synchronized (resource2) {
// Use both resources
}
}

// Thread B - MUST use same order


synchronized (resource1) {
synchronized (resource2) {
// Use both resources
}
}

3. GENERICS
3.1 Introduction to Generics

Java Generics is a powerful feature that enables you to write type-safe code that works with different
data types while maintaining compile-time type checking. This prevents runtime errors and eliminates
the need for explicit type casting.

3.2 Generic Classes

A generic class allows you to define a single class that can work with any data type. The type is
specified using a type parameter, typically represented by <T> .

Example:

class Box<T> {
private T value;

public void set(T value) {


[Link] = value;
}

public T get() {
return value;
}
}

public class Main {


public static void main(String[] args) {
// Box with String type
Box<String> stringBox = new Box<>();
[Link]("Hello");
[Link]("Value: " + [Link]());

// Box with Integer type


Box<Integer> intBox = new Box<>();
[Link](50);
[Link]("Value: " + [Link]());
}
}

3.3 Generic Methods

Generic methods allow you to define methods that work with any data type, independent of the class
they belong to. The type parameter is declared before the return type.

Example:

public class Main {


public static <T> void printArray(T[] array) {
for (T item : array) {
[Link](item);
}
}

public static void main(String[] args) {


String[] names = {"Jenny", "Liam"};
Integer[] numbers = {1, 2, 3};

printArray(names);
printArray(numbers);
}
}

3.4 Type Parameters


Type parameters are placeholders for actual data types that will be specified when the generic class or
method is used. Multiple type parameters are supported.

Example:

class Pair<K, V> {


private K key;
private V value;

public void set(K key, V value) {


[Link] = key;
[Link] = value;
}

public K getKey() {
return key;
}

public V getValue() {
return value;
}
}

public class Main {


public static void main(String[] args) {
Pair<String, Integer> pair = new Pair<>();
[Link]("Age", 25);
[Link]([Link]()); // Age
[Link]([Link]()); // 25
}
}

3.5 Bounded Type Parameters

Bounded type parameters restrict the types that can be used as type arguments. This is useful when you
need to ensure that the type has certain properties or methods.

Example:

class GenericsClass<T extends Number> {


public void display() {
[Link]("This is a bounded type generics class.");
}
}

public class Main {


public static void main(String[] args) {
GenericsClass<Integer> obj = new GenericsClass<>();
[Link]();
}
}

3.6 Wildcards
Wildcards provide flexibility when working with generic types. The wildcard ? represents an unknown
type.

Unbounded Wildcard:

public static void printList(List<?> list) {


for (Object item : list) {
[Link](item);
}
}

Upper Bounded Wildcard:

public static double sum(List<? extends Number> list) {


double sum = 0;
for (Number n : list) {
sum += [Link]();
}
return sum;
}

3.7 Generic Interfaces


Generic interfaces work similarly to generic classes and allow you to define interface contracts with
type parameters.

Example:

interface Container<T> {
void add(T item);
T get();
}

class Box<T> implements Container<T> {


private T item;

@Override
public void add(T item) {
[Link] = item;
}

@Override
public T get() {
return item;
}
}

3.8 Advantages of Generics

Type Safety: Catches type errors at compile time rather than runtime.

Elimination of Casting: No need for explicit casting when retrieving objects.

Code Reusability: Write a single generic class or method that works with multiple data types.

4. COLLECTIONS
4.1 Introduction to Collections Framework

The Java Collections Framework is a comprehensive set of interfaces and classes designed to store,
manipulate, and process collections of objects efficiently.

4.2 Collection Interfaces

Collection Interface: Root of the entire Java Collections Framework hierarchy. Defines fundamental
operations applicable to any collection.

List Interface: Represents an ordered collection (sequence). Maintains insertion order, allows duplicate
elements, and supports index-based access.

Set Interface: Represents an unordered collection with no duplicate elements.

Queue Interface: Represents a collection following FIFO (First-In-First-Out) order.

Map Interface: Stores key-value pairs rather than individual elements.

4.3 Collection Classes

List Implementations:

ArrayList: Resizable array implementation with fast random access


LinkedList: Doubly-linked list with fast insertion and deletion
Vector: Synchronized version of ArrayList (legacy)
Stack: Last-In-First-Out (LIFO) collection

Set Implementations:

HashSet: Unordered collection using hash table


TreeSet: Sorted collection maintaining elements in ascending order
LinkedHashSet: Maintains insertion order while using hash table

Queue Implementations:

PriorityQueue: Orders elements by priority


ArrayDeque: Double-ended queue implementation

Map Implementations:

HashMap: Unordered map using hash table


TreeMap: Sorted map maintaining keys in ascending order
LinkedHashMap: Maintains insertion order

4.4 Accessing a Collection via an Iterator

The Iterator interface provides a uniform way to traverse through elements in any collection.

Iterator Methods:

hasNext(): Returns true if more elements exist


next(): Returns the next element
remove(): Removes the current element

Example 1: Basic Iterator Usage


import [Link].*;

public class IteratorExample {


public static void main(String[] args) {
List<String> colors = new ArrayList<>();
[Link]("Red");
[Link]("Green");
[Link]("Blue");

Iterator<String> iterator = [Link]();

while ([Link]()) {
[Link]([Link]());
}
}
}

Example 2: Iterator with HashSet

import [Link].*;

public class SetIteratorExample {


public static void main(String[] args) {
Set<Integer> numbers = new HashSet<>();
[Link](10);
[Link](20);
[Link](30);

Iterator<Integer> iterator = [Link]();

while ([Link]()) {
int num = [Link]();
[Link]("Number: " + num);
}
}
}

Example 3: Using Iterator to Remove Elements

import [Link].*;

public class RemoveUsingIterator {


public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);

Iterator<Integer> iterator = [Link]();

while ([Link]()) {
int value = [Link]();
if (value % 2 == 0) {
[Link]();
}
}

[Link]("Remaining elements: " + list);


}
}
UNIT IV: EVENT HANDLING AND GUI
WITH SWING
1. EVENT HANDLING
1.1 Introduction to Event Handling

Java Event Handling is a mechanism that allows a program to respond to user interactions and system
events. It follows the Delegation Event Model, where events are generated by event sources, processed
by event classes, and handled by event listeners.

1.2 Events

An event occurs when a user interacts with a component. Events represent actions such as button clicks,
mouse movements, keyboard input, or window operations.

1.3 Event Sources


Event sources are UI components that generate events when users interact with them:

Button: Generates action events when pressed


Checkbox: Generates item events when selected/deselected
List: Generates action events on double-click
Scrollbar: Generates adjustment events
Text Components: Generate text events
Window: Generates window events

1.4 Event Classes

ActionEvent: Triggered by button clicks, menu selections. Methods include getActionCommand(),


getModifiers(), getWhen().

MouseEvent: Triggered by mouse interactions (MOUSE_CLICKED, MOUSE_DRAGGED,


MOUSE_ENTERED, MOUSE_EXITED, MOUSE_MOVED, MOUSE_PRESSED,
MOUSE_RELEASED). Methods include getX(), getY(), getClickCount(), getButton().

ItemEvent: Triggered by checkbox, choice, and list selections. Methods include getItem(),
getStateChange().

WindowEvent: Triggered during window lifecycle events. Methods include getWindow(),


getOldState(), getNewState().

KeyEvent: Triggered by keyboard input. Methods include getKeyChar(), getKeyCode().

1.5 Event Listeners


Event listeners are objects that implement specific listener interfaces to handle events.

Common Listener Interfaces:

ActionListener: actionPerformed()
MouseListener: mousePressed(), mouseClicked(), mouseEntered(), mouseExited(),
mouseReleased()
KeyListener: keyTyped(), keyPressed(), keyReleased()
ItemListener: itemStateChanged()
WindowListener: windowActivated(), windowClosed(), windowClosing(), etc.

1.6 Delegation Event Model


The Delegation Event Model operates through three steps:

1. An event occurs when a user interacts with a component


2. The component generates an event object
3. The event is passed to registered event listeners through callback methods

1.7 Handling Events

Example: Action Event Handling

import [Link].*;
import [Link].*;

class EventHandling extends Frame implements ActionListener {


TextField textField;

EventHandling() {
textField = new TextField();
[Link](60, 50, 170, 20);

Button button = new Button("Show");


[Link](90, 140, 75, 40);
[Link](this);

add(button);
add(textField);
setSize(250, 250);
setLayout(null);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


[Link]("Hello World");
}

public static void main(String args[]) {


new EventHandling();
}
}

Example: Mouse Event Handling

import [Link].*;
import [Link].*;

public class MouseEventDemo extends JFrame implements MouseListener {

public MouseEventDemo() {
addMouseListener(this);
setSize(300, 300);
setVisible(true);
}
public void mousePressed(MouseEvent e) {
int x = [Link]();
int y = [Link]();
[Link]("Mouse pressed at: " + x + ", " + y);
}

public void mouseClicked(MouseEvent e) {


[Link]("Mouse clicked " + [Link]() + " times");
}

public void mouseEntered(MouseEvent e) {


[Link]("Mouse entered component");
}

public void mouseExited(MouseEvent e) {


[Link]("Mouse exited component");
}

public void mouseReleased(MouseEvent e) {


[Link]("Mouse released");
}
}

Example: Keyboard Event Handling

import [Link].*;
import [Link].*;

public class KeyEventDemo extends JFrame implements KeyListener {

public KeyEventDemo() {
addKeyListener(this);
setSize(300, 300);
setVisible(true);
setFocusable(true);
}

public void keyPressed(KeyEvent e) {


[Link]("Key pressed: " + [Link]());
}

public void keyReleased(KeyEvent e) {


[Link]("Key released: " + [Link]());
}

public void keyTyped(KeyEvent e) {


[Link]("Key typed: " + [Link]());
}
}

2. GUI WITH SWING


2.1 Swing Introduction

Java Swing is part of the Java Foundation Classes (JFC) library that extends AWT and provides a
comprehensive set of tools for building graphical user interfaces. Swing is lightweight and offers
improved functionality with new components for creating modern desktop applications.

2.2 JApplet
JApplet is a Swing component that extends the [Link] class. It provides a way to create
applets with Swing components. However, applets are now deprecated in modern Java.

2.3 JFrame
JFrame is Swing's representation of a window and serves as the primary container for GUI applications.

Example:

import [Link];

public class MyGui {


public static void main(String[] args) {
JFrame frame = new JFrame("Happy Coding");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](300, 300);
[Link](true);
}
}

Key JFrame Methods:

setSize(width, height): Sets window dimensions


setDefaultCloseOperation(): Determines close button behavior
setVisible(true): Makes the frame visible
add(component): Adds components to the frame

2.4 JComponent

JComponent is the abstract base class for most Swing components, inheriting from [Link].
The hierarchy includes:

Containers: JFrame, JPanel, JWindow


Components: JLabel, JButton, JTextField, JTextArea
Advanced Components: JTable, JTree, JMenu

2.5 Icons and Labels


JLabel: Used to display text, images, or both in a GUI.

Example:

import [Link].*;
import [Link];

public class LabelExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Label Example");
[Link](JFrame.EXIT_ON_CLOSE);

JLabel label = new JLabel("Hello World!");


[Link](new Font("Serif", [Link], 36));
[Link]([Link]);

[Link](label);
[Link](300, 300);
[Link](true);
}
}

ImageIcon: Used to display images within labels or buttons.

Example:

import [Link].*;

ImageIcon icon = new ImageIcon("path/to/[Link]");


JLabel labelWithIcon = new JLabel(icon);
JLabel labelWithBoth = new JLabel("Click here", icon, [Link]);

2.6 Text Fields


JTextField: Allows users to input a single line of text.

Example:

import [Link].*;

public class TextFieldExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Text Field Example");
[Link](JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();


[Link](null);

JLabel label = new JLabel("Username:");


[Link](10, 20, 80, 25);
[Link](label);

JTextField textField = new JTextField(20);


[Link](100, 20, 150, 25);
[Link](textField);

[Link](panel);
[Link](300, 150);
[Link](true);
}
}

JPasswordField: Similar to JTextField but masks input for security.

JTextArea: Allows users to input and edit multiple lines of text.

2.7 Buttons - The JButton Class

JButton creates labeled buttons that users can click to trigger actions.

Example:

import [Link].*;
import [Link].*;

public class ButtonExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Button Example");
[Link](JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();


JButton button = new JButton("Click me!");

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("Button Clicked");
}
});

[Link](button);
[Link](panel);
[Link](300, 200);
[Link](true);
}
}

2.8 Check Boxes


JCheckBox is a graphical component that can be in either an on (true) or off (false) state. Multiple
checkboxes can be selected independently.

Example:

import [Link].*;

public class CheckBoxExample {


public static void main(String[] args) {
JFrame frame = new JFrame("CheckBox Example");
[Link](JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();

JCheckBox checkbox1 = new JCheckBox("Option 1");


JCheckBox checkbox2 = new JCheckBox("Option 2");
JCheckBox checkbox3 = new JCheckBox("Option 3");

[Link](checkbox1);
[Link](checkbox2);
[Link](checkbox3);

[Link](panel);
[Link](300, 200);
[Link](true);
}
}

2.9 Radio Buttons

JRadioButton is a graphical component that can be in either an on or off state within a group. Radio
buttons are mutually exclusive—only one button in a ButtonGroup can be selected at a time.

Example:

import [Link].*;

public class RadioButtonExample {


public static void main(String[] args) {
JFrame frame = new JFrame("RadioButton Example");
[Link](JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();

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


JRadioButton radio2 = new JRadioButton("Option 2");
JRadioButton radio3 = new JRadioButton("Option 3");

ButtonGroup group = new ButtonGroup();


[Link](radio1);
[Link](radio2);
[Link](radio3);

[Link](radio1);
[Link](radio2);
[Link](radio3);

[Link](panel);
[Link](300, 200);
[Link](true);
}
}

2.10 Combo Boxes


JComboBox presents the user with a dropdown menu of choices. This component is useful for saving
space while providing multiple selection options.

Example:

import [Link].*;

public class ComboBoxExample {


public static void main(String[] args) {
JFrame frame = new JFrame("ComboBox Example");
[Link](JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();

String[] options = {"Option 1", "Option 2", "Option 3", "Option 4"};
JComboBox<String> comboBox = new JComboBox<>(options);

[Link](new JLabel("Select an option:"));


[Link](comboBox);

[Link](panel);
[Link](300, 200);
[Link](true);
}
}

2.11 Tabbed Panes

JTabbedPane allows you to create multiple tabs within a single container, with each tab containing
different content.

Example:

import [Link].*;

public class TabbedPaneExample {


public static void main(String[] args) {
JFrame frame = new JFrame("TabbedPane Example");
[Link](JFrame.EXIT_ON_CLOSE);

JTabbedPane tabbedPane = new JTabbedPane();

JPanel panel1 = new JPanel();


[Link](new JLabel("This is Tab 1"));
[Link]("Tab 1", panel1);

JPanel panel2 = new JPanel();


[Link](new JLabel("This is Tab 2"));
[Link]("Tab 2", panel2);

JPanel panel3 = new JPanel();


[Link](new JLabel("This is Tab 3"));
[Link]("Tab 3", panel3);

[Link](tabbedPane);
[Link](300, 200);
[Link](true);
}
}

2.12 Scroll Panes


JScrollPane provides a scrollable view of a component when its contents exceed the visible area.

Example:

import [Link].*;

public class ScrollPaneExample {


public static void main(String[] args) {
JFrame frame = new JFrame("ScrollPane Example");
[Link](JFrame.EXIT_ON_CLOSE);

JTextArea textArea = new JTextArea(10, 30);


[Link]("This is a large text area.\n");
for (int i = 0; i < 50; i++) {
[Link]("Line " + (i + 1) + ": Some content here\n");
}

JScrollPane scrollPane = new JScrollPane(textArea);

[Link](scrollPane);
[Link](400, 300);
[Link](true);
}
}

2.13 Trees

JTree is designed to display hierarchical, tree-structured data where items have parent-child
relationships.

Example:

import [Link].*;
import [Link].*;

public class TreeExample extends JFrame {


public TreeExample() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");

DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Item 1");


DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Item 2");
DefaultMutableTreeNode grandchild = new DefaultMutableTreeNode("Item 1.1");

[Link](child1);
[Link](child2);
[Link](grandchild);

JTree tree = new JTree(root);


JScrollPane scrollPane = new JScrollPane(tree);
[Link](scrollPane);

[Link](JFrame.EXIT_ON_CLOSE);
[Link]("JTree Example");
[Link](300, 300);
[Link](true);
}

public static void main(String[] args) {


[Link](() -> new TreeExample());
}
}

2.14 Tables
JTable is used to display and edit two-dimensional data organized in rows and columns.

Example:

import [Link].*;

public class JTableExample extends JFrame {


public JTableExample() {
String[][] data = {
{"Kundan Kumar Jha", "4031", "CSE"},
{"Anand Jha", "6014", "IT"},
{"John Doe", "5012", "ECE"}
};

String[] columnNames = {"Name", "Roll Number", "Department"};

JTable table = new JTable(data, columnNames);


[Link](30, 40, 200, 300);

JScrollPane scrollPane = new JScrollPane(table);


[Link](scrollPane);

[Link](JFrame.EXIT_ON_CLOSE);
[Link]("JTable Example");
[Link](400, 300);
[Link](true);
}

public static void main(String[] args) {


[Link](() -> new JTableExample());
}
}

Key JTable Methods:


addColumn(TableColumn column): Adds a new column
clearSelection(): Clears all selected rows and columns
editCellAt(int row, int col): Programmatically edits a cell
getValueAt(int row, int col): Retrieves data from a cell
setValueAt(Object value, int row, int col): Sets data in a cell

SUMMARY
This comprehensive guide covers all topics from Unit 3 and Unit 4 of Object Oriented Programming:

Unit 3 covered Exception Handling (concepts, types, try-catch-finally, throw/throws, nested try, built-in
exceptions, custom exceptions), Multithreading (thread model, lifecycle, Thread class, Runnable
interface, synchronization, inter-thread communication, deadlock), Generics (generic methods, classes,
bounded types, wildcards, interfaces), and Collections (interfaces, classes, iterators).

Unit 4 covered Event Handling (events, sources, classes, listeners, delegation model) and GUI with
Swing (introduction, JApplet, JFrame, JComponent, Icons/Labels, text fields, buttons, checkboxes,
radio buttons, combo boxes, tabbed panes, scroll panes, trees, and tables).

Course: Object Oriented Programming (CS/CB/CD/CM/CO/IT216) Institution: R.V.R. & J.C. College
of Engineering (Autonomous), Guntur Semester: III (Second Year) Text Book: Java The Complete
Reference - Herbert Schildt, 11th Edition

END OF NOTES

You might also like