0% found this document useful (0 votes)
6 views39 pages

Java Multithreading Swings Notes

This document serves as a comprehensive exam preparation guide for Java programming, specifically focusing on multithreading and Swing GUI. It covers key concepts such as thread lifecycle, synchronization, and event handling, along with practical examples and experiment programs. The guide is structured into three parts: Multithreading, Swing GUI, and Experiment Programs, providing a thorough overview of essential Java programming topics.

Uploaded by

jhanvimangtani
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)
6 views39 pages

Java Multithreading Swings Notes

This document serves as a comprehensive exam preparation guide for Java programming, specifically focusing on multithreading and Swing GUI. It covers key concepts such as thread lifecycle, synchronization, and event handling, along with practical examples and experiment programs. The guide is structured into three parts: Multithreading, Swing GUI, and Experiment Programs, providing a thorough overview of essential Java programming topics.

Uploaded by

jhanvimangtani
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

Java Programming

Complete Notes: Multithreading & Swing GUI

FYBTECH | Exam Preparation Guide

Covers: Thread Lifecycle • Synchronization • Runnable Interface


Thread Methods • Swing Components • Event Handling • All Experiment Programs
TABLE OF CONTENTS
PART A: MULTITHREADING
1. Introduction to Multithreading
2. Thread vs Process
3. Thread Lifecycle
4. Creating Threads: Thread Class
5. Creating Threads: Runnable Interface
6. Thread Methods
7. Thread Synchronization
8. Inter-thread Communication (wait/notify)
9. Thread Priority
PART B: SWING GUI
10. Introduction to Swing
11. Swing Components
12. Event Handling
13. Layout Managers
PART C: PROGRAMS (Experiment 13 & 14)
14. All Experiment 13 Programs (Multithreading)
15. All Experiment 14 Programs (Swing)
16. Additional Important Programs
PART A: MULTITHREADING

1. Introduction to Multithreading
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilisation of CPU. Each part of such a program is called a thread. Threads are lightweight
sub-processes.

Why Multithreading?
• Better CPU utilisation — CPU doesn't sit idle while waiting for I/O.
• Improved application responsiveness — UI stays active while background tasks run.
• Faster execution of programs that can be divided into independent tasks.
• Resource sharing — threads share same memory space, unlike processes.

■ Note: Thread is the smallest unit of execution. A Java program by default runs in one thread called the 'main'
thread.

2. Thread vs Process
Feature Thread Process

Definition Lightweight sub-process Heavy-weight independent program

Memory Shares memory with other threads Has its own memory space

Communication Easy (shared memory) Complex (IPC mechanisms)

Creation Less time & resources More time & resources

Context Switch Faster Slower

Example Methods in same program Notepad, Chrome running together

3. Thread Lifecycle (States)


A thread goes through the following states during its lifetime:

NEW Thread object is created using new keyword but start() not yet called.

RUNNABLE Thread is ready to run. After start() is called. Waiting for CPU.

RUNNING Thread is currently executing. CPU is assigned to this thread.

BLOCKED/WAITING Thread is waiting for a resource/lock or waiting for another thread to notify it.

TIMED WAITING Thread waits for a specified time (e.g., sleep(1000) waits 1 second).

TERMINATED/DEAD Thread has finished execution or was stopped. Cannot be restarted.

Lifecycle diagram: NEW → RUNNABLE → RUNNING → BLOCKED/WAITING → RUNNABLE →


TERMINATED
4. Creating Threads: Extending Thread Class
The first way to create a thread is to extend the Thread class and override its run() method.

Steps:
• Create a class that extends Thread.
• Override the run() method — write the code you want to run in the thread.
• Create an object of your class.
• Call start() method — this internally calls run() in a new thread.

■ Note: NEVER call run() directly — that runs it in the same thread, not a new one! Always call start().

Basic Example:
class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + " - " + i);
try { [Link](500); } catch (InterruptedException e) {}
}
}
}

public class ThreadDemo {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
[Link]("Thread-A");
[Link]("Thread-B");
[Link](); // starts Thread-A
[Link](); // starts Thread-B
}
}

Output: Thread-A and Thread-B print numbers concurrently (order may vary).

5. Creating Threads: Implementing Runnable Interface


The second (and preferred) way to create a thread is by implementing the Runnable interface.

Why prefer Runnable over Thread?


• Java doesn't support multiple inheritance, so if your class extends Thread, it can't extend any other
class.
• Runnable allows your class to extend another class while still being runnable in a thread.
• Better design — separates task (what to do) from execution mechanism (thread).

Steps:
• Create a class that implements Runnable.
• Override the run() method.
• Create a Thread object passing your Runnable object.
• Call start() on the Thread object.
class MyTask implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + ": " + i);
try { [Link](300); } catch (InterruptedException e) {}
}
}
}

public class RunnableDemo {


public static void main(String[] args) {
MyTask task = new MyTask();
Thread t1 = new Thread(task, "Thread-1");
Thread t2 = new Thread(task, "Thread-2");
[Link]();
[Link]();
}
}

6. Important Thread Methods


Method Description

start() Starts a new thread and calls run() internally.

run() Contains the code to be executed by the thread.

sleep(ms) Pauses thread for specified milliseconds. Throws InterruptedException.

join() Waits for thread to finish before continuing. join(ms) waits max ms.

getName() Returns the name of the thread (default: Thread-0, Thread-1 ...).

setName(name) Sets a custom name for the thread.

getPriority() Returns thread priority (1 to 10). Default = 5.

setPriority(n) Sets thread priority. MIN=1, NORM=5, MAX=10.

isAlive() Returns true if thread has been started and not yet terminated.

currentThread() Static method. Returns reference to currently executing thread.

yield() Hints scheduler to give other threads a chance to run.

interrupt() Interrupts a sleeping/waiting thread. Sets interrupt flag.

wait() Makes thread wait (must be in synchronized block). From Object class.

notify() Wakes up ONE waiting thread. From Object class.

notifyAll() Wakes up ALL waiting threads. From Object class.

sleep() and join() Example:


class Worker extends Thread {
public void run() {
[Link]("Worker started");
try { [Link](2000); } catch (InterruptedException e) {}
[Link]("Worker done");
}
}

public class JoinDemo {


public static void main(String[] args) throws InterruptedException {
Worker w = new Worker();
[Link]();
[Link](); // main thread waits here until w finishes
[Link]("Main continues after Worker is done");
}
}

7. Thread Synchronization
Problem: When multiple threads access shared data simultaneously, they can corrupt it. This is called a
Race Condition.

Solution: Synchronization — allows only ONE thread at a time to access a shared resource. Java uses the
synchronized keyword.

7.1 Synchronized Method


Add synchronized keyword before method declaration. Only one thread can execute this method at a time.
class BankAccount {
private int balance = 1000;

public synchronized void withdraw(int amount) {


if (balance >= amount) {
[Link]([Link]().getName() + " withdrawing " + amount);
try { [Link](100); } catch (InterruptedException e) {}
balance -= amount;
[Link]("Remaining balance: " + balance);
} else {
[Link]("Insufficient funds for " + [Link]().getName());
}
}
}

class Customer extends Thread {


BankAccount account;
int amount;
Customer(BankAccount a, int amt, String name) {
super(name);
account = a;
amount = amt;
}
public void run() { [Link](amount); }
}

public class BankDemo {


public static void main(String[] args) {
BankAccount acc = new BankAccount();
Customer c1 = new Customer(acc, 700, "Alice");
Customer c2 = new Customer(acc, 700, "Bob");
[Link]();
[Link]();
}
}

7.2 Synchronized Block


More efficient — synchronizes only a part of the method instead of the entire method.
public void withdraw(int amount) {
[Link]([Link]().getName() + " waiting...");
synchronized(this) { // only this block is synchronized
if (balance >= amount) {
balance -= amount;
[Link]("Withdrawn. Balance: " + balance);
}
}
}

■ Note: synchronized(this) locks the current object. Only one thread can enter this block per object at a time.

8. Inter-Thread Communication: wait(), notify(), notifyAll()


These methods (from Object class) allow threads to communicate with each other. They must be called
inside a synchronized block/method.

Method What it does

wait() Releases lock and makes current thread WAIT until another thread calls notify()

notify() Wakes up ONE thread that is waiting on this object's lock

notifyAll() Wakes up ALL threads that are waiting on this object's lock

Producer-Consumer Example (wait/notify):


class SharedBuffer {
private int data;
private boolean hasData = false;

public synchronized void produce(int val) throws InterruptedException {


while (hasData) wait(); // wait if buffer full
data = val;
hasData = true;
[Link]("Produced: " + val);
notify(); // wake up consumer
}

public synchronized void consume() throws InterruptedException {


while (!hasData) wait(); // wait if buffer empty
[Link]("Consumed: " + data);
hasData = false;
notify(); // wake up producer
}
}

public class ProducerConsumer {


public static void main(String[] args) {
SharedBuffer buf = new SharedBuffer();
new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) [Link](i);
} catch (InterruptedException e) {}
}).start();
new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) [Link]();
} catch (InterruptedException e) {}
}).start();
}
}

9. Thread Priority
Java threads have a priority between 1 (MIN) and 10 (MAX). Default is 5 (NORM). Higher priority threads get
preference for CPU time (not guaranteed).

class MyThread extends Thread {


public void run() {
[Link](getName() + " Priority: " + getPriority() + " running");
}
}

public class PriorityDemo {


public static void main(String[] args) {
MyThread t1 = new MyThread(); [Link]("LOW");
MyThread t2 = new MyThread(); [Link]("NORMAL");
MyThread t3 = new MyThread(); [Link]("HIGH");

[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.NORM_PRIORITY); // 5
[Link](Thread.MAX_PRIORITY); // 10

[Link](); [Link](); [Link]();


}
}

■ Note: Thread priority is a hint to the scheduler. Actual execution order depends on JVM and OS.
PART B: SWING GUI PROGRAMMING

10. Introduction to Swing


Swing is Java's GUI (Graphical User Interface) toolkit. It provides a rich set of components to create
windows-based applications. Swing is part of the [Link] package.

• Swing is platform-independent (Write Once, Run Anywhere).


• Swing components are lightweight (drawn by Java, not OS).
• All Swing components start with 'J': JFrame, JButton, JLabel, etc.
• Swing is built on top of AWT (Abstract Window Toolkit).

Basic Structure of a Swing Application:


import [Link].*; // import all Swing components
import [Link].*; // import AWT for layouts, colors
import [Link].*; // import for event handling

public class BasicWindow extends JFrame {


public BasicWindow() {
setTitle("My First Swing App");
setSize(400, 300); // width x height in pixels
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // center on screen
setVisible(true); // make it visible
}
public static void main(String[] args) {
new BasicWindow();
}
}

11. Swing Components


Here are all the commonly used Swing components:

Component Description

JFrame Main window container. Every Swing app has one JFrame.

JPanel Invisible container to group other components. Used for layout.

JLabel Displays text or image. Non-editable.

JButton Clickable button. Triggers action when clicked.

JTextField Single-line text input box.

JTextArea Multi-line text input/display area.

JPasswordField Like JTextField but hides characters (shows dots).

JCheckBox Tick box — can be selected/deselected independently.

JRadioButton Round button — only one in a ButtonGroup can be selected.

JComboBox Drop-down list to select one option.


JList Shows a list of items. Can select one or multiple.

JMenuBar Horizontal menu bar at the top of the window.

JMenu A menu inside the MenuBar (File, Edit, etc.).

JMenuItem Clickable item inside a JMenu.

JScrollPane Adds scroll bars to a component (e.g., JTextArea).

JTable Displays data in rows and columns.

JSlider Allows selecting a value by dragging a knob.

JProgressBar Shows progress of an operation.

JDialog Pop-up dialog window.

JOptionPane Ready-made dialog boxes (message, input, confirm).

ButtonGroup Groups radio buttons so only one is selected at a time.

12. Event Handling


Events are actions performed by the user (clicking, typing, hovering). Java uses the Event Delegation
Model to handle events.

3 Steps to Handle an Event:


• Step 1 — Create Event Source: The component that generates the event (e.g., JButton).
• Step 2 — Create Event Listener: An object that listens for the event (implements listener interface).
• Step 3 — Register Listener: Attach listener to source using addXxxListener() method.

Listener Interface Method(s) Used For

ActionListener actionPerformed(ActionEvent e) Button click, menu selection, Enter in text field

MouseListener mouseClicked, mousePressed, mouseReleased, mouseEntered,


Mouse mouseExited
button events

KeyListener keyPressed, keyReleased, keyTyped Keyboard key events

WindowListener windowClosing, windowOpened, etc. Window events

ItemListener itemStateChanged(ItemEvent e) Checkbox, radio button, combobox selection

FocusListener focusGained, focusLost Component focus events

13. Layout Managers


Layout Managers control how components are arranged inside a container.

Layout Description

FlowLayout Components arranged left-to-right, top-to-bottom (default for JPanel).

BorderLayout 5 regions: NORTH, SOUTH, EAST, WEST, CENTER (default for JFrame).

GridLayout Components in equal-sized cells in a grid. GridLayout(rows, cols).

BoxLayout Arranges components in single row or column.

GridBagLayout Most flexible, complex. Components can span multiple cells.

null layout You set exact x, y, width, height using setBounds(). No auto-arrangement.

null Layout Example (setBounds):


JFrame f = new JFrame();
[Link](null); // no layout manager
JButton btn = new JButton("Click Me");
[Link](50, 100, 120, 35); // x, y, width, height
[Link](btn);
PART C: ALL EXPERIMENT PROGRAMS

EXPERIMENT 13: MULTITHREADING PROGRAMS


13a. Two threads: Thread-1 prints 1-5, Thread-2 prints A-E concurrently
class NumberThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread-1 (Numbers): " + i);
try { [Link](500); } catch (InterruptedException e) {}
}
}
}

class CharThread extends Thread {


public void run() {
for (char c = 'A'; c <= 'E'; c++) {
[Link]("Thread-2 (Chars): " + c);
try { [Link](500); } catch (InterruptedException e) {}
}
}
}

public class TwoThreadsDemo {


public static void main(String[] args) {
NumberThread t1 = new NumberThread();
CharThread t2 = new CharThread();
[Link]();
[Link]();
}
}

/* Sample Output (order varies):


Thread-1 (Numbers): 1
Thread-2 (Chars): A
Thread-1 (Numbers): 2
Thread-2 (Chars): B ... */

13b. Two child threads from same class displaying pattern /*/*/*
class PatternThread extends Thread {
public PatternThread(String name) {
super(name);
}
public void run() {
for (int i = 0; i < 5; i++) {
[Link](getName() + ": /*/*/*");
try { [Link](400); } catch (InterruptedException e) {}
}
}
}

public class PatternDemo {


public static void main(String[] args) {
PatternThread child1 = new PatternThread("Child-1");
PatternThread child2 = new PatternThread("Child-2");
[Link]();
[Link]();
}
}

13c. Parent thread creates child to calculate sum of first n numbers, parent waits
class SumThread extends Thread {
int n;
int result;

SumThread(int n) { this.n = n; }

public void run() {


result = 0;
for (int i = 1; i <= n; i++) {
result += i;
try { [Link](100); } catch (InterruptedException e) {}
}
[Link]("Child: Sum calculated = " + result);
}
}

public class ParentChildSum {


public static void main(String[] args) throws InterruptedException {
[Link]("Parent: Creating child thread");
SumThread child = new SumThread(10);
[Link]();
[Link]("Parent: Waiting for child to finish...");
[Link](); // parent waits here
[Link]("Parent: Child finished. Result = " + [Link]);
}
}

/* Output:
Parent: Creating child thread
Parent: Waiting for child to finish...
Child: Sum calculated = 55
Parent: Child finished. Result = 55 */

13d. Two threads share a single bank account — synchronization ensures consistency
class BankAccount {
private double balance;

public BankAccount(double initialBalance) {


[Link] = initialBalance;
}

public synchronized void withdraw(double amount) {


[Link]([Link]().getName() + " trying to withdraw: " + amount);
if (balance >= amount) {
try { [Link](100); } catch (InterruptedException e) {}
balance -= amount;
[Link]([Link]().getName() + " SUCCESS. Balance: " + balance);
} else {
[Link]([Link]().getName() + " FAILED. Insufficient funds.");
}
}

public double getBalance() { return balance; }


}

class AccountThread extends Thread {


private BankAccount account;
private double amount;

AccountThread(String name, BankAccount acc, double amt) {


super(name);
account = acc;
amount = amt;
}

public void run() {


[Link](amount);
}
}

public class BankSyncDemo {


public static void main(String[] args) throws InterruptedException {
BankAccount account = new BankAccount(1000.0);

AccountThread t1 = new AccountThread("Alice", account, 700.0);


AccountThread t2 = new AccountThread("Bob", account, 700.0);

[Link]();
[Link]();
[Link]();
[Link]();

[Link]("Final Balance: " + [Link]());


}
}

13e. setName and getName demo


class NamedThread extends Thread {
public void run() {
[Link]("Thread running: " + getName());
}
}

public class SetGetNameDemo {


public static void main(String[] args) {
NamedThread t1 = new NamedThread();
NamedThread t2 = new NamedThread();

[Link]("WorkerThread-1");
[Link]("WorkerThread-2");

[Link]("Thread 1 name: " + [Link]());


[Link]("Thread 2 name: " + [Link]());

[Link]();
[Link]();
}
}

13f. Thread waits using wait(), another thread notifies using notify() — inter-thread
communication
class Shared {
synchronized void waitingThread() throws InterruptedException {
[Link]("Waiting thread: About to wait...");
wait(); // releases lock and waits
[Link]("Waiting thread: Got notified! Resuming.");
}

synchronized void notifyingThread() throws InterruptedException {


[Link](2000); // simulate some work
[Link]("Notifying thread: Printing 1 to 5...");
for (int i = 1; i <= 5; i++) [Link](i);
notify(); // wake up the waiting thread
[Link]("Notifying thread: Notified!");
}
}
public class WaitNotifyDemo {
public static void main(String[] args) {
Shared obj = new Shared();

Thread t1 = new Thread(() -> {


try { [Link](); } catch (InterruptedException e) {}
});

Thread t2 = new Thread(() -> {


try { [Link](); } catch (InterruptedException e) {}
});

[Link]();
[Link]();
}
}

13g. Create two threads, set names, print names 5 times, set different priorities
class PriorityThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](getName() + " (Priority: " + getPriority() + ") - Run " + i);
try { [Link](200); } catch (InterruptedException e) {}
}
}
}

public class NamePriorityDemo {


public static void main(String[] args) {
PriorityThread t1 = new PriorityThread();
PriorityThread t2 = new PriorityThread();

[Link]("HIGH-PRIORITY-THREAD");
[Link]("LOW-PRIORITY-THREAD");

[Link](Thread.MAX_PRIORITY); // 10
[Link](Thread.MIN_PRIORITY); // 1

[Link]();
[Link]();
}
}
EXPERIMENT 14: SWING GUI PROGRAMS
14a. Login Form: LoginID + Password → display on OK, clear on RESET
import [Link].*;
import [Link].*;
import [Link].*;

public class LoginForm extends JFrame implements ActionListener {


JLabel lblLogin, lblPass, lblResult;
JTextField tfLogin, tfResult;
JPasswordField pfPass;
JButton btnOK, btnReset;

public LoginForm() {
setTitle("Login");
setSize(420, 220);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

lblLogin = new JLabel("Login ID:");


[Link](30, 30, 80, 25);
add(lblLogin);

tfLogin = new JTextField();


[Link](120, 30, 150, 25);
add(tfLogin);

lblPass = new JLabel("Password:");


[Link](30, 70, 80, 25);
add(lblPass);

pfPass = new JPasswordField();


[Link](120, 70, 150, 25);
add(pfPass);

btnOK = new JButton("OK");


[Link](30, 110, 80, 30);
[Link](this);
add(btnOK);

btnReset = new JButton("RESET");


[Link](120, 110, 80, 30);
[Link](this);
add(btnReset);

lblResult = new JLabel("Combined:");


[Link](30, 150, 80, 25);
add(lblResult);

tfResult = new JTextField();


[Link](120, 150, 250, 25);
[Link](false);
add(tfResult);

setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if ([Link]() == btnOK) {
String id = [Link]();
String pass = new String([Link]());
[Link]("ID: " + id + " | Pass: " + pass);
} else if ([Link]() == btnReset) {
[Link]("");
[Link]("");
[Link]("");
}
}

public static void main(String[] args) {


new LoginForm();
}
}

14b. Basic Calculator


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

public class Calculator extends JFrame implements ActionListener {


JTextField display;
double num1, num2, result;
char operator;
boolean startNew = true;

String[] buttons = {
"7","8","9","/",
"4","5","6","*",
"1","2","3","-",
"0","C","=","+"
};

public Calculator() {
setTitle("Calculator");
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout(5, 5));
setLocationRelativeTo(null);

display = new JTextField("0");


[Link](new Font("Arial", [Link], 24));
[Link]([Link]);
[Link](false);
add(display, [Link]);

JPanel panel = new JPanel(new GridLayout(4, 4, 5, 5));


for (String text : buttons) {
JButton btn = new JButton(text);
[Link](new Font("Arial", [Link], 18));
[Link](this);
[Link](btn);
}
add(panel, [Link]);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String cmd = [Link]();
if ([Link]("C")) {
[Link]("0");
startNew = true;
} else if ("0123456789".contains(cmd)) {
if (startNew) { [Link](cmd); startNew = false; }
else [Link]([Link]() + cmd);
} else if ([Link]("=")) {
num2 = [Link]([Link]());
switch(operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = (num2 != 0) ? num1 / num2 : 0; break;
}
[Link]([Link](result));
startNew = true;
} else {
num1 = [Link]([Link]());
operator = [Link](0);
startNew = true;
}
}
public static void main(String[] args) { new Calculator(); }
}

14c. Registration Form — Display selected fields in Details after Submit is clicked
import [Link].*;
import [Link].*;
import [Link].*;

public class RegistrationForm extends JFrame implements ActionListener {


JTextField tfName;
JRadioButton rbMale, rbFemale;
JCheckBox cbMusic, cbSwimming;
JComboBox<String> cbPlace;
JTextArea taDetails;
JButton btnSubmit, btnExit;
ButtonGroup genderGroup;

public RegistrationForm() {
setTitle("Registration Form");
setSize(450, 420);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Name
add(makeLabel("Name:", 20, 20));
tfName = new JTextField();
[Link](130, 20, 200, 25);
add(tfName);

// Gender
add(makeLabel("Gender:", 20, 60));
rbMale = new JRadioButton("Male"); [Link](130, 60, 70, 25);
rbFemale = new JRadioButton("Female"); [Link](210, 60, 80, 25);
genderGroup = new ButtonGroup();
[Link](rbMale);
[Link](rbFemale);
[Link](true);
add(rbMale); add(rbFemale);

// Interests
add(makeLabel("Interest:", 20, 100));
cbMusic = new JCheckBox("Music"); [Link](130, 100, 80, 25);
cbSwimming = new JCheckBox("Swimming"); [Link](220, 100, 90, 25);
add(cbMusic); add(cbSwimming);
// Favourite Place
add(makeLabel("Favourite Place:", 20, 140));
String[] places = {"Bangladesh", "India", "USA", "UK", "Japan"};
cbPlace = new JComboBox<>(places);
[Link](130, 140, 150, 25);
add(cbPlace);

// Details
add(makeLabel("Details:", 20, 180));
taDetails = new JTextArea();
[Link](false);
JScrollPane sp = new JScrollPane(taDetails);
[Link](130, 180, 270, 100);
add(sp);

// Buttons
btnSubmit = new JButton("Submit");
[Link](100, 300, 90, 30);
[Link](this);
add(btnSubmit);

btnExit = new JButton("Exit");


[Link](210, 300, 90, 30);
[Link](this);
add(btnExit);

setVisible(true);
}

JLabel makeLabel(String text, int x, int y) {


JLabel l = new JLabel(text);
[Link](x, y, 110, 25);
return l;
}

public void actionPerformed(ActionEvent e) {


if ([Link]() == btnSubmit) {
String name = [Link]();
String gender = [Link]() ? "Male" : "Female";
String interest = "";
if ([Link]()) interest += "Music ";
if ([Link]()) interest += "Swimming";
String place = (String) [Link]();

[Link](
"Name: " + name + "\n" +
"Gender: " + gender + "\n" +
"Interest: " + interest + "\n" +
"Favourite Place: " + place
);
} else if ([Link]() == btnExit) {
[Link](0);
}
}

public static void main(String[] args) { new RegistrationForm(); }


}
ADDITIONAL IMPORTANT PROGRAMS

MULTITHREADING — EXTRA PROGRAMS


P1. Daemon Thread Demo
Daemon threads are background threads that stop automatically when all non-daemon threads finish. GC is
a daemon thread.
class DaemonThread extends Thread {
public void run() {
while (true) {
[Link]("Daemon running: " + getName());
try { [Link](500); } catch (InterruptedException e) { break; }
}
}
}

public class DaemonDemo {


public static void main(String[] args) throws InterruptedException {
DaemonThread dt = new DaemonThread();
[Link](true); // set BEFORE start()
[Link]("Daemon");
[Link]();

[Link]("Is daemon? " + [Link]());


[Link](2000); // main thread sleeps 2 seconds
[Link]("Main thread ending — daemon will auto-stop");
}
}

P2. Multiple Threads using Runnable (Lambda style)


public class LambdaThreadDemo {
public static void main(String[] args) {
// Using lambda expression (Java 8+)
Thread t1 = new Thread(() -> {
for (int i = 1; i <= 5; i++)
[Link]("Thread-1: " + i);
});

Thread t2 = new Thread(() -> {


for (char c = 'A'; c <= 'E'; c++)
[Link]("Thread-2: " + c);
});

[Link]();
[Link]();
}
}

P3. Thread isAlive() and join() demo


class Task extends Thread {
public void run() {
try { [Link](2000); } catch (InterruptedException e) {}
[Link]("Task complete!");
}
}

public class AliveDemo {


public static void main(String[] args) throws InterruptedException {
Task t = new Task();
[Link]("Before start: isAlive = " + [Link]());
[Link]();
[Link]("After start: isAlive = " + [Link]());
[Link](); // wait for t to finish
[Link]("After join: isAlive = " + [Link]());
}
}

P4. Thread interrupt() demo


class SleepThread extends Thread {
public void run() {
try {
[Link]("Thread going to sleep for 10 seconds...");
[Link](10000);
[Link]("Thread woke up normally");
} catch (InterruptedException e) {
[Link]("Thread was interrupted! " + [Link]());
}
}
}

public class InterruptDemo {


public static void main(String[] args) throws InterruptedException {
SleepThread t = new SleepThread();
[Link]();
[Link](2000); // wait 2 seconds
[Link](); // interrupt the sleeping thread
}
}

P5. Counter without synchronization (shows Race Condition problem)


class Counter {
int count = 0;
void increment() { count++; } // NOT synchronized — race condition!
}

public class RaceConditionDemo {


public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) [Link]();
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) [Link]();
});

[Link](); [Link]();
[Link](); [Link]();

[Link]("Expected: 2000, Got: " + [Link]);


// Output varies and is often less than 2000 due to race condition
}
}

P6. Counter WITH synchronization (fix for Race Condition)


class SyncCounter {
int count = 0;
synchronized void increment() { count++; } // synchronized — thread-safe
}

public class SyncCounterDemo {


public static void main(String[] args) throws InterruptedException {
SyncCounter c = new SyncCounter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) [Link]();
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) [Link]();
});

[Link](); [Link]();
[Link](); [Link]();

[Link]("Count (always 2000): " + [Link]);


}
}

P7. Print Even and Odd numbers alternately using two threads
class EvenOddPrinter {
int num = 1;
int max = 10;

synchronized void printOdd() throws InterruptedException {


while (num <= max) {
if (num % 2 == 0) wait();
else {
[Link]("Odd Thread: " + num);
num++;
notify();
}
}
}

synchronized void printEven() throws InterruptedException {


while (num <= max) {
if (num % 2 != 0) wait();
else {
[Link]("Even Thread: " + num);
num++;
notify();
}
}
}
}

public class EvenOddDemo {


public static void main(String[] args) {
EvenOddPrinter printer = new EvenOddPrinter();
new Thread(() -> {
try { [Link](); } catch (InterruptedException e) {}
}).start();
new Thread(() -> {
try { [Link](); } catch (InterruptedException e) {}
}).start();
}
}

P8. Three threads printing messages in sequence


class SequenceThread extends Thread {
String message;
int count;
SequenceThread(String msg, int count, int priority) {
[Link] = msg;
[Link] = count;
setPriority(priority);
}
public void run() {
for (int i = 0; i < count; i++) {
[Link](getName() + ": " + message);
try { [Link](300); } catch (InterruptedException e) {}
}
}
}

public class ThreeThreadsDemo {


public static void main(String[] args) {
SequenceThread t1 = new SequenceThread("Hello", 3, Thread.MAX_PRIORITY);
SequenceThread t2 = new SequenceThread("World", 3, Thread.NORM_PRIORITY);
SequenceThread t3 = new SequenceThread("Java!", 3, Thread.MIN_PRIORITY);
[Link](); [Link](); [Link]();
}
}
SWING — EXTRA PROGRAMS
P9. Simple Window with JLabel and JButton
import [Link].*;
import [Link].*;

public class SimpleWindow extends JFrame {


public SimpleWindow() {
setTitle("Simple Window");
setSize(350, 200);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

JLabel lbl = new JLabel("Hello, Swing!");


[Link](100, 40, 150, 30);
add(lbl);

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


[Link](100, 90, 120, 30);
[Link](e -> [Link]("Button Clicked!"));
add(btn);

setVisible(true);
}
public static void main(String[] args) { new SimpleWindow(); }
}

P10. Counter App — Increment, Decrement, Reset


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

public class CounterApp extends JFrame {


int count = 0;
JLabel display;

public CounterApp() {
setTitle("Counter");
setSize(300, 200);
setLayout(new FlowLayout([Link], 20, 30));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

display = new JLabel("Count: 0", [Link]);


[Link](new Font("Arial", [Link], 20));
add(display);
JButton btnInc = new JButton("+");
JButton btnDec = new JButton("-");
JButton btnRst = new JButton("Reset");

[Link](e -> { count++; [Link]("Count: " + count); });


[Link](e -> { count--; [Link]("Count: " + count); });
[Link](e -> { count = 0; [Link]("Count: 0"); });

add(btnInc); add(btnDec); add(btnRst);


setVisible(true);
}
public static void main(String[] args) { new CounterApp(); }
}

P11. Text Reverser App


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

public class TextReverser extends JFrame {


JTextField input, output;
JButton btnReverse;

public TextReverser() {
setTitle("Text Reverser");
setSize(400, 200);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

add(new JLabel("Input:")).setBounds(20, 30, 70, 25);


// cleaner approach:
JLabel l1 = new JLabel("Input:"); [Link](20,30,70,25); add(l1);
JLabel l2 = new JLabel("Reversed:"); [Link](20,75,70,25); add(l2);

input = new JTextField(); [Link](100, 30, 250, 25); add(input);


output = new JTextField(); [Link](100, 75, 250, 25);
[Link](false); add(output);

btnReverse = new JButton("Reverse"); [Link](140, 120, 100, 30);


[Link](e -> {
String rev = new StringBuilder([Link]()).reverse().toString();
[Link](rev);
});
add(btnReverse);
setVisible(true);
}
public static void main(String[] args) { new TextReverser(); }
}

P12. Color Changer using Radio Buttons


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

public class ColorChanger extends JFrame implements ActionListener {


JPanel colorPanel;
JRadioButton rbRed, rbGreen, rbBlue, rbYellow;

public ColorChanger() {
setTitle("Color Changer");
setSize(350, 300);
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

colorPanel = new JPanel();


[Link]([Link]);
[Link](new Dimension(350, 180));
add(colorPanel, [Link]);

JPanel radioPanel = new JPanel(new FlowLayout());


rbRed = new JRadioButton("Red");
rbGreen = new JRadioButton("Green");
rbBlue = new JRadioButton("Blue");
rbYellow = new JRadioButton("Yellow");

ButtonGroup bg = new ButtonGroup();


for (JRadioButton rb : new JRadioButton[]{rbRed,rbGreen,rbBlue,rbYellow}) {
[Link](rb); [Link](rb); [Link](this);
}
add(radioPanel, [Link]);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if ([Link]() == rbRed) [Link]([Link]);
if ([Link]() == rbGreen) [Link]([Link]);
if ([Link]() == rbBlue) [Link]([Link]);
if ([Link]() == rbYellow) [Link]([Link]);
}

public static void main(String[] args) { new ColorChanger(); }


}
P13. CheckBox Interests Display
import [Link].*;
import [Link].*;
import [Link].*;

public class CheckBoxDemo extends JFrame implements ActionListener {


JCheckBox cbReading, cbCoding, cbGaming, cbCooking;
JLabel lblResult;
JButton btnShow;

public CheckBoxDemo() {
setTitle("Interests");
setSize(350, 250);
setLayout(new FlowLayout([Link], 20, 20));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

add(new JLabel("Select your interests:"));


cbReading = new JCheckBox("Reading");
cbCoding = new JCheckBox("Coding");
cbGaming = new JCheckBox("Gaming");
cbCooking = new JCheckBox("Cooking");
add(cbReading); add(cbCoding); add(cbGaming); add(cbCooking);

btnShow = new JButton("Show Interests");


[Link](this);
add(btnShow);

lblResult = new JLabel("");


add(lblResult);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


StringBuilder sb = new StringBuilder("You like: ");
if ([Link]()) [Link]("Reading ");
if ([Link]()) [Link]("Coding ");
if ([Link]()) [Link]("Gaming ");
if ([Link]()) [Link]("Cooking");
[Link]([Link]());
}

public static void main(String[] args) { new CheckBoxDemo(); }


}

P14. ComboBox — City Selection


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

public class ComboBoxDemo extends JFrame {


JComboBox<String> cityBox;
JLabel lblSelected;

public ComboBoxDemo() {
setTitle("City Selector");
setSize(350, 180);
setLayout(new FlowLayout([Link], 20, 30));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

add(new JLabel("Select City:"));


String[] cities = {"Mumbai", "Delhi", "Bangalore", "Pune", "Chennai"};
cityBox = new JComboBox<>(cities);
add(cityBox);

JButton btn = new JButton("Select");


lblSelected = new JLabel("No city selected");

[Link](e ->
[Link]("Selected: " + [Link]())
);

add(btn); add(lblSelected);
setVisible(true);
}
public static void main(String[] args) { new ComboBoxDemo(); }
}

P15. JOptionPane — Message, Input and Confirm Dialogs


import [Link].*;

public class DialogDemo {


public static void main(String[] args) {
// 1. Message dialog
[Link](null, "Welcome to Java Swing!", "Info",
JOptionPane.INFORMATION_MESSAGE);

// 2. Input dialog
String name = [Link](null, "Enter your name:");

// 3. Confirm dialog
int choice = [Link](null,
"Hello " + name + "! Continue?", "Confirm",
JOptionPane.YES_NO_OPTION);

if (choice == JOptionPane.YES_OPTION)
[Link](null, "You chose YES!");
else
[Link](null, "You chose NO!");
}
}

P16. Menu Bar with File Menu (Open, Save, Exit)


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

public class MenuDemo extends JFrame implements ActionListener {


JTextArea textArea;

public MenuDemo() {
setTitle("Menu Demo");
setSize(450, 350);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Create menu bar


JMenuBar menuBar = new JMenuBar();

// File menu
JMenu fileMenu = new JMenu("File");
JMenuItem miNew = new JMenuItem("New");
JMenuItem miOpen = new JMenuItem("Open");
JMenuItem miSave = new JMenuItem("Save");
JMenuItem miExit = new JMenuItem("Exit");

for (JMenuItem mi : new JMenuItem[]{miNew, miOpen, miSave, miExit}) {


[Link](this);
[Link](mi);
}

// Edit menu
JMenu editMenu = new JMenu("Edit");
JMenuItem miCopy = new JMenuItem("Copy");
JMenuItem miPaste = new JMenuItem("Paste");
[Link](miCopy); [Link](miPaste);

[Link](fileMenu);
[Link](editMenu);
setJMenuBar(menuBar);
textArea = new JTextArea("Type here...");
add(new JScrollPane(textArea));
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String cmd = [Link]();
switch(cmd) {
case "New": [Link](""); break;
case "Exit": [Link](0); break;
default: [Link](this, cmd + " clicked");
}
}

public static void main(String[] args) { new MenuDemo(); }


}

P17. Student Marks Entry Form with GridLayout


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

public class MarksForm extends JFrame implements ActionListener {


JTextField tfName, tfMaths, tfScience, tfEnglish, tfTotal, tfPercent;
JButton btnCalc, btnClear;

public MarksForm() {
setTitle("Student Marks Form");
setSize(380, 320);
setLayout(new GridLayout(8, 2, 8, 8));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

String[] labels = {"Student Name:","","Maths:","",


"Science:","","English:","",
"Total:","","Percentage:",""};

add(new JLabel("Student Name:")); tfName = new JTextField(); add(tfName);


add(new JLabel("Maths (100):")); tfMaths = new JTextField(); add(tfMaths);
add(new JLabel("Science (100):")); tfScience = new JTextField(); add(tfScience);
add(new JLabel("English (100):")); tfEnglish = new JTextField(); add(tfEnglish);
add(new JLabel("Total:")); tfTotal = new JTextField(); [Link](false);
add(tfTotal);
add(new JLabel("Percentage:")); tfPercent = new JTextField();
[Link](false); add(tfPercent);

btnCalc = new JButton("Calculate"); [Link](this);


btnClear = new JButton("Clear"); [Link](this);
add(btnCalc); add(btnClear);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


if ([Link]() == btnCalc) {
try {
int m = [Link]([Link]());
int s = [Link]([Link]());
int en = [Link]([Link]());
int total = m + s + en;
double pct = total / 3.0;
[Link]([Link](total));
[Link]([Link]("%.2f%%", pct));
} catch (NumberFormatException ex) {
[Link](this, "Enter valid numbers!");
}
} else {
[Link](""); [Link]("");
[Link](""); [Link]("");
[Link](""); [Link]("");
}
}
public static void main(String[] args) { new MarksForm(); }
}

P18. Font Changer — Bold, Italic using CheckBoxes


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

public class FontChanger extends JFrame implements ActionListener {


JLabel lblText;
JCheckBox cbBold, cbItalic;
JSlider sizeSlider;

public FontChanger() {
setTitle("Font Changer");
setSize(400, 280);
setLayout(new FlowLayout([Link], 20, 20));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

lblText = new JLabel("Hello, Java Swing!");


[Link](new Font("Arial", [Link], 20));
add(lblText);
cbBold = new JCheckBox("Bold");
cbItalic = new JCheckBox("Italic");
[Link](this);
[Link](this);
add(cbBold); add(cbItalic);

add(new JLabel("Font Size:"));


sizeSlider = new JSlider(10, 50, 20);
[Link](10);
[Link](true);
[Link](true);
[Link](ce -> updateFont());
add(sizeSlider);
setVisible(true);
}

void updateFont() {
int style = [Link];
if ([Link]()) style |= [Link];
if ([Link]()) style |= [Link];
[Link](new Font("Arial", style, [Link]()));
}

public void actionPerformed(ActionEvent e) { updateFont(); }


public static void main(String[] args) { new FontChanger(); }
}

P19. Swing with Multithreading: Progress Bar simulation


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

public class ProgressDemo extends JFrame {


JProgressBar progressBar;
JButton btnStart;
JLabel lblStatus;

public ProgressDemo() {
setTitle("Progress Bar");
setSize(400, 180);
setLayout(new FlowLayout([Link], 20, 20));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

progressBar = new JProgressBar(0, 100);


[Link](new Dimension(300, 25));
[Link](true);
add(progressBar);

btnStart = new JButton("Start");


lblStatus = new JLabel("Press Start");
add(btnStart); add(lblStatus);

[Link](e -> {
[Link](false);
new Thread(() -> {
for (int i = 0; i <= 100; i++) {
final int val = i;
[Link](() -> {
[Link](val);
[Link](val == 100 ? "Done!" : "Loading: " + val + "%");
if (val == 100) [Link](true);
});
try { [Link](50); } catch (InterruptedException ex) {}
}
}).start();
});
setVisible(true);
}
public static void main(String[] args) { new ProgressDemo(); }
}

■ Note: [Link]() is used to update Swing components from a non-EDT thread safely. Always
update UI from the Event Dispatch Thread (EDT).
QUICK REVISION CHEAT SHEET

Multithreading — Key Points to Remember


• Thread class: extend Thread, override run(), call start() — NEVER run() directly.
• Runnable interface: implement Runnable, override run(), pass to Thread constructor.
• sleep(ms): static method, pauses CURRENT thread for ms milliseconds.
• join(): makes calling thread wait until the target thread finishes.
• synchronized: ensures only one thread accesses the block/method at a time.
• wait(): releases lock, thread waits. Must be in synchronized block.
• notify(): wakes ONE waiting thread. notifyAll() wakes ALL.
• setPriority(n): 1=MIN, 5=NORM, 10=MAX. Higher priority = more CPU preference.
• setName()/getName(): assign/retrieve custom names for threads.
• isAlive(): true if thread started and not yet dead.
• Daemon thread: setDaemon(true) before start(). Stops when main ends.
• Race condition: two threads modify shared data simultaneously → wrong result.

Swing — Key Points to Remember


• Always import [Link].* and [Link].* and [Link].*
• JFrame: main window. setSize(), setVisible(true), setDefaultCloseOperation().
• setLayout(null): use setBounds(x, y, width, height) for each component.
• add(component): add component to the frame/panel.
• ActionListener: implement it, override actionPerformed(), use addActionListener().
• [Link](): identify which component triggered the event.
• [Link](): get the text/command of the component.
• ButtonGroup: group radio buttons so only one is selected at a time.
• [Link](): quick popup message.
• JScrollPane: wrap JTextArea/JList for scroll functionality.
• [Link](): update Swing UI from background thread safely.
• getText()/setText(): get or set text in JTextField, JTextArea, JLabel.
• isSelected(): check if JCheckBox or JRadioButton is selected.
• getSelectedItem(): get selected item from JComboBox.

Best of luck for your exam! ■


You've got this — practice the programs and understand the concepts!

You might also like