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

APP - Unit 3

The document outlines advanced Java programming paradigms, focusing on concurrent programming, multithreading, and multitasking. It explains the concepts of shared memory and message passing in concurrent programming, as well as the lifecycle of threads in Java. Additionally, it provides examples of creating threads and discusses the importance of thread management in Java applications.
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 views127 pages

APP - Unit 3

The document outlines advanced Java programming paradigms, focusing on concurrent programming, multithreading, and multitasking. It explains the concepts of shared memory and message passing in concurrent programming, as well as the lifecycle of threads in Java. Additionally, it provides examples of creating threads and discusses the importance of thread management in Java applications.
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/ 127

21CSC203P -Advanced Programming

Practice
Unit-3
Advanced Java Programming Paradigms

APP Faculties
Department of Computational Intelligence
SRM Institute of Science and Technology

14-09-2023 APP Faculties - CINTEL 1


Outline of the Presentation

S-19: Concurrent Programming Paradigm


S-20: Multithreading and Multitasking
S-21: Thread classes and methods
S-22: Declarative Programming Paradigm: Java Database Connectivity
(JDBC)
S-22: Connectivity with MySQL – Query Execution
S-23: Graphical User Interface Based Programming Paradigm
S-24: Java Applets-Basics
S-24: Java Swing
S-25: Model View Controller (MVC) and Widgets
14-09-2023 Dr.Maivizhi Assistant Professor-/ CINTEL
APP Faculties CINTEL 2
Concurrent Programming Paradigm
• Computing systems model the world, and the world contains actors that execute independently of, but communicate with,
each other. In modelling the world, many (possibly) parallel executions have to be composed and coordinated, and that's
where the study of concurrency comes in.
• There are two common models for concurrent programming: shared memory and message passing.
• Shared memory. In the shared memory model of concurrency, concurrent modules interact by reading and writing
shared objects in memory.
• Message passing. In the message-passing model, concurrent modules interact by sending messages to each other
through a communication channel. Modules send off messages, and incoming messages to each module are queued up
for handling

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL


APP Faculties - CINTEL 3
APP Faculties - CINTEL 4
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
14-09-2023 APP Faculties - CINTEL 5
APP Faculties - CINTEL 6
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
APP Faculties - CINTEL 7
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
APP Faculties - CINTEL 8
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Issues Concurrent Programming Paradigm
Concurrent programming is programming with multiple tasks. The major issues of concurrent programming are:
• Sharing computational resources between the tasks;
• Interaction of the tasks.

Objects shared by multiple tasks have to be safe for concurrent access. Such objects are called protected. Tasks accessing such an
object, interact with each other indirectly through the object.
An access to the protected object can be:
• Lock-free, when the task accessing the object is not blocked for a considerable time;
• Blocking, otherwise.
Blocking objects can be used for task synchronization. To the examples of such objects belong:
• Events;
• Mutexes and semaphores;
• Waitable timers;
• Queues

APP Faculties - CINTEL 9


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Multitasking
• Two tasks simultaneously in computers: Word and listening to music
• These two tasks are called processes.
• Multitasking: Start typing in word and listening to music
• Now if a machine is dual-core then one process or task is been handled by
one core and music is been handled by another core.
• Committed a mistake in a Word and spell check shows exception, this
means Word is a process that is broken down into sub-processes.
• In this way the mechanism of dividing the tasks is called multithreading in
which every process or task is called by a thread.
• Thread is responsible for when to execute, when to stop and how long to
be in a waiting state.
• Hence, a thread is the smallest unit of processing whereas multitasking is
a process of executing multiple tasks at a time.
Ways of achieving multitasking
• Multi processing
• Multi tasking

14-09-2023 APP Faculties - CINTEL 11


Process-based multitasking (Multiprocessing)

• Process-based multitasking is the more familiar form.

• A process is, in essence, a program that is executing. Thus, process-based multitasking is the feature that allows your
computer to run two or more programs concurrently.

• For example, process-based multitasking enables you to run the Java compiler at the same time that you are using a text
editor.

• In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.

• Each process has an address in memory. In other words, each process allocates a separate memory area.

• A process is heavyweight.

• Cost of communication between the process is high.

• Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists,
etc.

APP Faculties - CINTEL 12


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Thread-based multitasking (Multithreading)
• Thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means that
a single program can perform two or more tasks simultaneously.

• For instance, a text editor can format text at the same time that it is printing, as long as these two actions are
being performed by two separate threads.

• Thus, process-based multitasking deals with the “big picture,” and thread-based multitasking handles the
details.

• Threads share the same address space.

• A thread is lightweight.

• Cost of communication between the thread is low.

APP Faculties - CINTEL 13


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Multithreaded Programming
• Java provides built-in support for multithreaded programming.

• A multithreaded program contains two or more parts that can run concurrently. Each part of such a
program is called a thread, and each thread defines a separate path of execution. Thus,
multithreading is a specialized form of multitasking.

• There are two distinct types of multitasking: process-based and thread-based.

• It is important to understand the difference between the two.

APP Faculties - CINTEL 14


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Thread in Java
• A thread in Java is the direction or path that is taken while a program is being executed.

• All the programs have at least one thread, known as the main thread, that is provided by the JVM or Java
Virtual Machine at the starting of the program’s execution.

• main() method is invoked by the main thread.

• Multiple threads of execution can be run concurrently by an application running on the Java Virtual Machine.
The priority of each thread varies.

• Higher priority threads are executed before lower priority threads.

• Thread is critical in the program because it enables multiple operations to take place within a single method.

APP Faculties - CINTEL 15


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Creating a Thread in Java

• A thread in Java can be created in the following two ways:

• Extending java.lang.Thread class

• Implementing Runnable interface

APP Faculties - CINTEL 16


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Extending java.lang.Thread class

public class MyThread extends Thread {


public void run() {
System.out.println("This code is running in a thread");
}
public static void main(String[] args) {
MyThread obj = new MyThread();
obj.start();
}
}
Output:
This code is running in a thread

APP Faculties - CINTEL 17


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Extending java.lang.Thread class
public class MyThread implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
public static void main(String[] args) {
Thread obj = new Thread(new MyThread());
obj.start();
}
}
Output:
This code is running in a thread

The start() method is used to call the void run() method. When start() is called, a new stack is given to the thread, and
run() is invoked to introduce a new thread in the program.

APP Faculties - CINTEL 18


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Lifecycle of a Thread

• The Life Cycle of a Thread in Java refers to the state transformations of a thread that begins with
its birth and ends with its death.
• When a thread instance is generated and executed by calling the start() method of the Thread
class, the thread enters the runnable state. When the sleep() or wait() methods of the Thread class
are called, the thread enters a non-runnable mode.
• Thread returns from non-runnable state to runnable state and starts statement execution. The
thread dies when it exits the run() process. In Java, these thread state transformations are
referred to as the Thread life cycle.
• There are basically 4 stages in the lifecycle of a thread, as given below:
• New
• Runnable
• Running
• Blocked (Non-runnable state)
• Dead

APP Faculties - CINTEL 19


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Lifecycle of a Thread
1. New: When a thread is just created enters start() method.
2. Runnable: A thread in the runnable state is prepared to execute
the code. When a new thread's start() function is called, it enters a
runnable state.
In the runnable environment, the thread is ready for execution
and is awaiting the processor's availability (CPU time). That is,
the thread has entered the queue (line) of threads waiting for
execution
3. Running: Running implies that the processor (CPU) has
assigned a time slot to the thread for execution. When a
thread from the runnable state is chosen for execution by
the thread scheduler, it joins the running state..
4. Blocked: When the thread is alive, i.e., the thread class object
persists, but it cannot be selected for execution by the scheduler. It is
now inactive.
5. Terminated: When a thread's run() function ends the execution
of sentences, it automatically dies or enters the dead state.
That is, when a thread exits the run() process, it is terminated
or killed. When the stop() function is invoked, a thread will
also go dead.

APP Faculties - CINTEL 20


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
The value of the variable amount is
unpredictable
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println(amount);
amount++;
System.out.println(amount);
}
public void run() {
amount++;
14-09-2023 APP Faculties - CINTEL 21
Commonly used Constructors of Thread class
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r,String name)

14-09-2023 APP Faculties - CINTEL 22


Thread Class and the Runnable Interface

• Java’s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable.
Thread encapsulates a thread of execution.

• The Thread class defines several methods that help manage threads.

APP Faculties - CINTEL 23


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Using the Thread Class: Thread(String Name)
public class MyThread1
{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String name)
Thread t= new Thread("My first thread");

// the start() method moves the thread to the active state


t.start();
// getting the thread name by invoking the getName() method
String str = t.getName();
System.out.println(str);
}
}
Output:

My first thread
14-09-2023 APP Faculties - CINTEL 24
Using the Thread Class: Thread(Runnable r, String
name)
public class MyThread2 implements Runnable
{
public void run()
{
System.out.println("Now the thread is running ...");
}
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");

// the start() method moves the thread to the active state


th1.start();
14-09-2023 APP Faculties - CINTEL 25
Thread.sleep() in Java
• Syntax of the sleep() method:
1. public static void sleep(long mls) throws InterruptedException
2. public static void sleep(long mls, int n) throws InterruptedException
• mls: The time in milliseconds is represented by the parameter mls. The duration
for which the thread will sleep is given by the method sleep().
• n: It shows the additional time up to which the programmer or developer wants the
thread to be in the sleeping state. The range of n is from 0 to 999999.
• The method does not return anything.
• Whenever the Thread.sleep() methods execute, it always halts the execution of
the current thread.
• Whenever another thread does interruption while the current thread is already
in the sleep mode, then the InterruptedException is thrown.
14-09-2023 APP Faculties - CINTEL 26
Thread.sleep() in Java

class TestSleepMethod1 extends Thread{


public void run(){
for(int i=1;i<5;i++){
// the thread will sleep for the 500 milli seconds
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();
t2.start();
}
} APP Faculties - CINTEL 27
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
• In this program, a reference to the current thread (the main thread, in this case) is
Example:
obtained by calling currentThread( ), and this reference is stored in the local variable
t.

• Next, the program displays information about the thread. The program then calls
setName( ) to change the internal name of the thread. Information about the thread is
then redisplayed.

• Next, a loop counts down from five, pausing one second between each line. The pause
is accomplished by the sleep( ) method.

• The argument to sleep( ) specifies the delay period in milliseconds. Notice the
try/catch block around this loop.

• The sleep( ) method in Thread might throw an InterruptedException.

• This would happen if some other thread wanted to interrupt this sleeping one.

• This example just prints a message if it gets interrupted. In a real program, you would
need to handle this differently.

Output
APP Faculties - CINTEL 28
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Example that creates a new thread and starts it running

Output
APP Faculties - CINTEL 29
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Extending Thread (Continue…)

Creating Multiple Threads

• This program generates the same output as the preceding


version.
• Child thread is created by instantiating an object of
NewThread, which is derived from Thread.

APP Faculties - CINTEL 30


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Creating Multiple Threads

APP Faculties - CINTEL 31


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL Output
Using is Alive( ) and join( )

• The main thread to finish last. In the preceding examples, this is accomplished by calling sleep( ) within main( ), with a
long enough delay to ensure that all child threads terminate prior to the main thread.

• Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the thread. This method is
defined by Thread, and its general form is shown here:

final boolean isAlive( )

• The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise.

• While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called
join( ), shown here:

final void join( ) throws InterruptedException

APP Faculties - CINTEL 32


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
join() Method
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1(); 123451122334455
t1.start();
try{
t1.join();
14-09-2023 APP Faculties - CINTEL 33
Naming a thread in java
class TestMultiNaming1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());

t1.start();
t2.start();

t1.setName(“Java thread");
System.out.println("After changing name of t1:"+t1.getName());
14-09-2023 APP Faculties - CINTEL 34
}
Example

APP Faculties - CINTEL 35


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Example

Output
APP Faculties - CINTEL 36
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Thread Priorities

• Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run.

• To set a thread’s priority, use the setPriority( ) method, which is a member of Thread. This is its general form:

final void setPriority(int level)

• Here, level specifies the new priority setting for the calling thread. The value of level must be within the range
MIN_PRIORITY and MAX_PRIORITY.

• Currently, these values are 1 and 10, respectively. To return a thread to default priority, specify NORM_PRIORITY,
which is currently 5. These priorities are defined as final variables within Thread.

• You can obtain the current priority setting by calling the getPriority( ) method of Thread, shown here:

final int getPriority( )

APP Faculties - CINTEL 37


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY
• Default priority of a thread is 5 (NORM_PRIORITY).
• The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY
is 10.

14-09-2023 APP Faculties - CINTEL 38


// Importing the required classes
import java.lang.*;
public class ThreadPriorityExample extends Thread
{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
// Creating threads with the help of ThreadPriorityExample class
ThreadPriorityExample th1 = new ThreadPriorityExample();
ThreadPriorityExample th2 = new ThreadPriorityExample();
ThreadPriorityExample th3 = new ThreadPriorityExample();
// Displaying the priority of the thread using the getPriority() method
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());

// Display the priority of the thread


System.out.println("Priority of the thread th2 is : " + th2.getPriority());
14-09-2023
// Setting APP Faculties - CINTEL
priorities of above threads by passing integer arguments 39
Java Database Connectivity (JDBC)
• JDBC stands for Java Database Connectivity. JDBC is a Java API to
connect and execute the query with the database. It is a part of JavaSE
(Java Standard Edition). JDBC API uses JDBC drivers to connect with
the database.
• JDBC API to access tabular data stored in any relational database. By
the help of JDBC API, we can save, update, delete and fetch data from
the database.

APP Faculties - CINTEL 40


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
JDBC Connection Steps
There are 6 basic steps to connect with JDBC.

APP Faculties - CINTEL 41


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Import Packages

• First, to import the existing packages to use it in our Java program.


Import will make sure that JDBC API classes are available for the
program. We can then use the classes and subclasses of the packages.
import java.sql.*;
JDBC API 4.0 mainly provides 2 important packages:
• java.sql
• javax.sql

APP Faculties - CINTEL 42


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
java.sql package
This package provides classes and interfaces to perform most of the JDBC functions like creating and executing
SQL queries.

APP Faculties - CINTEL 43


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
javax.sql package
• It is a JDBC extension API and provides server-side data access and
processing in Java Program.

APP Faculties - CINTEL 44


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Load Driver
First, we should load/register the driver in the program before connecting
to the Database. You need to register it only once per database in the
program.

We can load the driver in the following 2 ways:

1. Class.forName()
2. DriverManager.registerDriver()

APP Faculties - CINTEL 45


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Class.forName()
In this way, the driver’s class file loads into the memory at runtime. It
implicitly loads the driver. While loading, the driver will register with
JDBC automatically.

APP Faculties - CINTEL 46


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
DriverManager.registerDriver()
DriverManager is an inbuilt class that is available in the java.sql package.
It acts as a mediator between Java application and database which you want to connect. Before you
connect with the database, you need to register the driver with DriverManager.
The main function of DriverManager is to load the driver class of the Database and create a connection
with DB.
• Public static void registerDriver(driver) – This method will register the driver with the Driver
Manager. If the driver is already registered, then it won’t take any action.
• It will throw SQLException if the database error occurs.
• It will throw NullPointerException if the driver is null.

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver())

APP Faculties - CINTEL 47


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Establish Connection
After loading the driver, the next step is to create and establish the connection. Once
required, packages are imported and drivers are loaded and registered, then we can
go for establishing a Database connection.
DriverManager class has the getConnection method, we will use this method to get
the connection with Database.
To call getConnection() method, we need to pass 3 parameters. The 3 parameters are
string data type URL, a username, and a password to access the database.
• The getConnection() method is an overloaded method. The 2 methods are:
• getConnection(URL,username,password); – It has 3 parameters URL, username,
password.
• getConnection(URL); – It has only one parameter. URL has a username and
password also.

APP Faculties - CINTEL 48


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Establish Connection
The following table lists the JDBC connection strings for the different databases:

Example:

Connection con =
DriverManager.getConnection(jdbc:oracle:thin:@localhost
:1521:xe,System,Pass123@)

Here in this example,


•thin refers to the Driver type.
•localhost is where the Oracle database is running.
•1521 is the port number to connect to DB.
•xe – SID
•System – User name to connect to the Oracle Database.
•Pass123@ – Password

APP Faculties - CINTEL 49


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Create And Execute Statement
Once the connection has established, we can interact with the connected Database. First, we need to create the
statement to perform the SQL query and then execute the statement.

(i) Create Statement


Now we will create the statement object that runs the query with the connected database. We use the
createStatement method of the Connection class to create the query.

There are 3 statement interfaces are available in the java.sql package. These are explained below:

a) Statement

This interface is used to implement simple SQL statements with no parameter. It returns the ResultSet object.

Statement statemnt1 = conn.createStatement();

APP Faculties - CINTEL 50


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Create And Execute Statement
b) PreparedStatement
This PreparedStatement interface extends the Statement interface. So, it
has more features than the Statement interface. It is used to implement
parameterized and precompiled SQL statements. The performance of
the application increases because it compiles the query only once.
• It is easy to reuse this interface with a new parameter. It supports the
IN parameter. Even we can use this statement without any parameter.

String select_query = “Select * from states where state_id = 1”;


PreparedStatement prpstmt = conn.prepareStatement(select_query);

APP Faculties - CINTEL 51


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Create And Execute Statement
c) CallableStatement

CallableStatement interface extends the PreparedStatement interface. So, it


has more features than the PreparedStatement interface. It is used to
implement a parameterized SQL statement that invokes procedure or function
in the database. A stored procedure works like a method or function in a class.
It supports the IN and OUT parameters.

• The CallableStatement instance is created by calling the prepareCall method


of the Connection object.

CallableStatementcallStmt = con.prepareCall("{call procedures(?,?)}");

APP Faculties - CINTEL 52


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Create And Execute Statement
(ii) Execute The Query
There are 4 important methods to execute the query in Statement interface. These are explained below:
• ResultSet executeQuery(String sql) a) ResultSet executeQuery(String sql)
The executeQuery() method in Statement interface is used to execute the
• int executeUpdate(String sql) SQL query and retrieve the values from DB. It returns the ResultSet object.
Normally, we will use this method for the SELECT query.
• boolean execute(String sql)
• int []executeBatch() b) executeUpdate(String sql)
The executeUpdate() method is used to execute value specified queries like
INSERT, UPDATE, DELETE (DML statements), or DDL statements that return
nothing. Mostly, we will use this method for inserting and updating.

c) execute(String sql)
The execute() method is used to execute the SQL query. It returns true if it
executes the SELECT query. And, it returns false if it executes INSERT or
UPDATE query.

d) executeBatch()
This method is used to execute a batch of SQL queries to the Database and
if all the queries get executed successfully, it returns an array of update
APP Faculties - CINTEL 53
14-09-2023 Dr.Maivizhi counts.
Assistant We/ CINTEL
Professor will use this method to insert/update the bulk of records .
Retrieve Results
• When we execute the queries using the executeQuery() method, the result will be stored
in the ResultSet object.
• The returned ResultSet object will never be null even if there is no matching record in the
table. ResultSet object is used to access the data retrieved from the Database.
ResultSet rs 1= statemnt1.executeQuery(QUERY));
• The executeQuery() method for the SELECT query. When someone tries to execute the
insert/update query, it will throw SQLExecption with the message “executeQuery method
can not be used for update”.
• A ResultSet object points to the current row in the Resultset. To iterate the data in the
ResultSet object, call the next() method in a while loop. If there is no more record to read,
it will return FALSE.
• ResultSet can also be used to update data in DB. We can get the data from ResultSet using
getter methods such as getInt(), getString(), getDate(). We need to pass the column index
or column name as the parameter to get the values using Getter methods.

APP Faculties - CINTEL 54


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Close Connection
• To close the JDBC connection. need to make sure that we have closed the resource after
we have used it. If we don’t close them properly we may end up out of connections.
• When we close the connection object, Statement and ResultSet objects will be closed
automatically.
conn.close();
• From Java 7 onwards, we can close the JDBC connections automatically using a try-catch
block. JDBC connection should be opened in the parenthesis of the try block. Inside the
try block, you can do the database connections normally as we do.
• Once the execution exits the try block, it will automatically close the connection. In this
case, we don’t need to close the connection by calling conn.close method in the Java
program.
try(Connection conn = DriverManager.getConnection(url, user, password))
{
//database connection and operation
}
APP Faculties - CINTEL 55
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Java JDBC Connection Example
Implement the 6 basic steps to connect with database using JDBC in Java program.
Create Table
• Before that, first, create one table and add some entries into it.
• Below is the SQL query to create a table.

create table employee_details (empNum number(10), lastName varchar(50), firstName varchar(50),


email varchar(255) , deptNum number(10), salary number(10));

Insert Data Into Table


• Using the following queries, insert the data into the “employee_details” table.

insert into employee_details values (1001, 'Luther', 'Martin', '[email protected]', 1, 13000);


insert into employee_details values (1002, 'Murray', 'Keith', '[email protected]', 2, 25000);
insert into employee_details values (1003, 'Branson', 'John', '[email protected]', 3, 15000);
insert into employee_details values (1004, 'Martin', 'Richard', '[email protected]', 4, 16000);
insert into employee_details values (1005, 'Hickman', 'David', '[email protected]', 5, 17000);

APP Faculties - CINTEL 56


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Java Program - Oracle
import java.sql.*; //Get the values of the record using while loop
public class Sample_JDBC_Program { while(rs1.next())
public static void main(String[] args) throws {
ClassNotFoundException, SQLException { int empNum = rs1.getInt("empNum");
// store the SQL statement in a string String lastName = rs1.getString("lastName");
String QUERY = "select * from employee_details“ String firstName = rs1.getString("firstName");
//register the oracle driver with DriverManager String email = rs1.getString("email");
Class.forName("oracle.jdbc.driver.OracleDriver"); String deptNum = rs1.getString("deptNum");
/*Here we have used Java 8 so opening the connection in try String salary = rs1.getString("salary");
statement*/ //store the values which are retrieved using ResultSet and print it
try(Connection conn = System.out.println(empNum + "," +lastName+ "," +firstName+ ","
DriverManager.getConnection("jdbc:oracle:thin:system/pass123@ +email +","+deptNum +"," +salary);
localhost:1521:XE")) }
{ }
Statement statemnt1 = conn.createStatement(); }
//Created statement and execute it catch (SQLException e) {
ResultSet rs1 = statemnt1.executeQuery(QUERY); //If exception occurs catch it and exit the program
{ e.printStackTrace();
}
}
}

APP Faculties - CINTEL 57


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
Java Program - Mysql
import java.sql.*;
public class javamysql {
public static void main(String arg[])
{ Connection connection = null;
try {
// below two lines are used for connectivity.
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","mydbuser", "mydbuser");
// mydb is database; mydbuser is name of database ;mydbuser is password of database
Statement statement;
statement = connection.createStatement();
ResultSet resultSet;
resultSet = statement.executeQuery("select * from designation");
int code;
String title;
while (resultSet.next()) {
code = resultSet.getInt("code");
title = resultSet.getString("title").trim();
System.out.println("Code : " + code + " Title : " + title);
}
resultSet.close();
statement.close();
connection.close();
}
catch (Exception exception) {
System.out.println(exception);
}
} APP Faculties - CINTEL 58
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL
}
JAVA APPLETS

Learning Objectives:
• Introduction
CUI (Character User Interface)
GUI (Graphical User Interface)
Abstract Window Toolkit (AWT)
• What are Applets in Java?
Applet Basics
Life Cycle of an Applet
Types of Applets in Java
How to run an Applet
Sample Applet Programs
Advantages and Disadvantages
Applet Features over HTML

14-09-2023 14-09-2023 Dr.Maivizhi Assistant Professor


APP /Faculties
CINTEL- CINTEL 59
JAVA APPLETS
Introduction
There are two ways that users can interact with the programme:
They are:
CUI (Character User Interface)
GUI (Graphical User Interface)

• Character User Interface(CUI):


In CUI user interacts with the application by typing characters or commands. In CUI user should remember the commands.
It is not user friendly.
Example: In a Java program, we can add two numbers(integers) , declare the numbers, do the addition, and report the
results. It makes it hard for the end user to understand how to interact with this program throughout compilation and
execution (feed input and get outcomes).
Let's take into consideration that the aforementioned program can have the user-friendly (GUI) following configuration:
Enter number 1 (integer) + Enter number 2 (integer) = Result (Addition of Two integer numbers)

Whenever the end-user compile the program, can enter two numbers in the given space and clicking on the “equal button”, can get
the results in the specified space, which is easy to understand. This is an example for GUI for addition of two numbers.

14-09-2023
14-09-2023 Dr.Maivizhi Assistant Professor- CINTEL
APP Faculties / CINTEL 60
JAVA APPLETS
• Graphical User Interface (GUI)
Java Abstract Window Toolkit (AWT) is an Application Program Interface (API) to develop GUI or window-based
application in java. The Abstract Window Toolkit(AWT) support for applets. The AWT contains numerous classes and methods
that allow you to create and manage the GUI window.

Abstract Window Toolkit (AWT)


• AWT is an Application programming interface (API) for creating Graphical User Interface (GUI) in Java. It allows Java
programmers to develop window-based applications.
• AWT represents a class library to develop applications using GUI.
• AWT provides various components like button, label, checkbox, etc. used as objects inside a Java Program. AWT components
use the resources of the operating system, i.e., they are platform-dependent, which means, component's view can be changed
according to the view of the operating system. The classes for AWT are provided by the Java.awt package for various AWT
components.
• The Java.awt package contains classes and interfaces that help create graphical user interfaces and enable more user-friendly
programme interaction.

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 61
JAVA APPLETS
The hierarchy of Java AWT :

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 62
JAVA APPLETS
• Object Class:
Object class is the superclass of all Java classes. All Java classes inherited from this class.
• Component Class:
The component class, which takes the top position in the AWT hierarchy, is an abstract class that contains all of
the component's screen-visible characteristics. The Component object gives details about the foreground and
background colours that are currently selected. Additionally, it provides information about the presently selected
font colour.
• Container:
A component called the container includes additional components like a button, textfield, label, etc. It is a subclass
of the Component class, too.
• Panel:
The panel can be defined as a container that can be used to hold other components. However, it doesn't contain the
title bar, menu bar, or border.
• Window:
A window can be defined as a container that doesn't contain any border or menu bar. It creates a top-level view.
However, we must have a frame, dialog, or another window for creating a window.
• Frame:
The frame is a subclass of Window. It can be defined as a container with components like button, textfield, label,
etc. In other words, AWT applications are mostly created using frame container.

14-09-2023 14-09-2023 APP Faculties


Dr.Maivizhi Assistant Professor / CINTEL - CINTEL 63
JAVA APPLETS
What are Applets in Java?
The interactive components of web applications are provided by Java applets, which can be easily run by many
different platforms' browsers. They can launch automatically when the pages are browsed and are tiny, portable Java
programmes embedded in HTML pages.
• Applet inherits awt Component class and awt Container class

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 64
JAVA APPLETS
Applet Basics:
• All applets are subclasses of Applet. Thus, all applets must import java.applet. Applets must also import java.awt package.

• Applets are not executed by the console-based Java run-time interpreter. Rather, they are executed by either a Web browser
or an applet viewer.

• Execution of an applet does not begin at main( ) [In other words, there is no main() method in an Applet]. Output to your
applet’s window is not performed by System.out.println( ). Rather, it is handled with various AWT methods, such as
drawString( ), which outputs a string to a specified X,Y location. Input is also handled differently than in an application.

• Once an applet has been compiled, it is included in an HTML file using the APPLET tag. The applet will be executed by a
Java-enabled web browser when it encounters the APPLET tag within the HTML file.

• To view and test an applet more conveniently, simply include a comment at the head of your Java source code file that
contains the APPLET tag.

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 65
JAVA APPLETS
Java applets are one of three kinds of Java programs:

• An application is a standalone program that can be invoked from the command line.

• An applet is a program that runs in the context of a browser session.

• A servlet is a program that is invoked on demand on a server program and that runs in
the context of a web server process.

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 66
JAVA APPLETS
• Applets are programs stored on a web server, like web pages.
• When an applet is referred to in a web page that has been fetched and processed by a browser, the browser
generates a request to fetch (or download) the applet program, then executes the program in the browser’s
execution context, on the client host.

14-09-2023 14-09-2023 APP Faculties


Dr.Maivizhi Assistant Professor / CINTEL - CINTEL 67
JAVA APPLETS
Life Cycle of an Applet
It's essential in understanding the sequence whereby the
different methods indicated in the figure are invoked. The
following methods are called in this order when an applet
begins:

1.init( )
2.start( )
3.paint( )

When an applet is terminated, the following sequence of method


calls takes place:

1.stop( )
2.destroy( )

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 68
JAVA APPLETS

• public void init(): is used to initialized the Applet. It is invoked only once.
• public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
• public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
• public void destroy(): is used to destroy the Applet. It is invoked only once.
• public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc etc.
Within the method paint() we will call the drawString() method to print a
text message in the applet window.

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 69
JAVA APPLETS
Types of Applets in Java
1. Local Applet
2. Remote Applet
Local Applet
• Local Applet is developed locally and stored in the local system. A web page doesn't need the get the information
from the internet when it finds the local Applet in the system. It is specified or defined by the file name or pathname.
There are two attributes used in defining an applet, i.e., the codebase that specifies the path name and code that
defined the name of the file that contains Applet's code..

• Example:
<applet
codebase = “MyOwnApplet"
code = “FirstApplet.class"
width = 120
height = 120>
</applet>

14-09-2023 14-09-2023 Dr.Maivizhi Assistant Professor


APP /Faculties
CINTEL- CINTEL 70
JAVA
JAVA APPLETS
APPLETS
Remote Applet
• Remote applets are stored in a remote computer and an Internet connection is needed to access them. The remote
applet is designed and developed by other developers. To find and load a remote applet, you need to know the
address of the network applet, i.e., the Uniform Resource Locator (URL).

• Example:

<applet
codebase = "http://www.myconnect.com/applets/"
code = "FirstApplet.class"
width = 120
height =120>
</applet>

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 71
JAVA
JAVA APPLETS
APPLETS
Difference between Local Applet and Remote Applet:

Local Applet Remote Applet

There is no need to define the Applet's URL We need to define the Applet's URL in
in Local Applet. Remote Applet.
Local Applet is available on our computer. Remote Applet is not available on our
computer.
To use it or access it, we don't need Internet To use it or access it on our computer, we
Connection. need an Internet Connection.
It is written on our own and then embedded It was written by another developer.
into the web pages.
We don't need to download it. It is available on a remote computer, so we
need to download it to our system.

14-09-2023 14-09-2023 Dr.Maivizhi Assistant Professor


APP /Faculties
CINTEL- CINTEL 72
JAVA
JAVA APPLETS
APPLETS
How to run an applet
An applet can be run two ways:
1. Through HTML file.
2. Using the appletviewer tool (for testing purposes).
1. Through HTML file:
For an applet to run in a web browser, we must write a short HTML text file that
contains a tag to load an applet. For this, we can use <applet> or <object> tags. The
HTML <applet> tag specifies an applet. It embeds Java applets in HTML documents. It
does not support HTML5.

14-09-2023 14-09-2023 Dr.Maivizhi Assistant Professor


APP /Faculties
CINTEL- CINTEL 73
JAVA
JAVA APPLETS
APPLETS
Through HTML file:
<!DOCTYPE html>
<html>

<head>
<title>HTML applet Tag</title>
</head>

<body>
<applet code = “FirstApplet.class" width = "300" height = "200"></applet>
</body>

</html>

• In the HTML text file above, the code attribute of the <applet> tag specifies the applet class to execute.
• The width and height attributes are also required. They define the initial size of the panel on which the
applet is running.
• The applet command must be closed with the </applet> tag.

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 74
JAVAAPPLETS
JAVA APPLETS
Below is the applet class embedded in the HTML file above:

import java.applet.*;
import java.awt.*;

public class FirstApplet extends Applet


{
public void paint (Graphics gh)
{
gh.drawString(“Weclome to my first applet..!”,300, 150);
}
}

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 75
JAVA
JAVA APPLETS
APPLETS
2. Using the appletviewer tool:
The appletviewer runs an applet in the window. It is usually the fastest and easiest way to test an applet. Create an applet
containing the <applet> tag in the comment and compile it. It is for testing purposes only.

//FirstApplet.java
import java.applet.Applet;
import java.awt.Graphics;
public class FirstApplet extends Applet
{ To run an applet using the appletviewer tool, write in the
public void paint(Graphics g) command prompt:
{
g.drawString("welcome to my first applet",10,50); c:\>javac FirstApplet.java
} c:\>appletviewer FirstApplet.java
} c:\>appletviewer FirstApplet.html

/* This is saved as FirstApplet.html Here,


<applet code="FirstApplet.class" width="300" • javac is the compiler that compiles java codes using a command
height="300"> line.
</applet> • FirstApplet.java is the applet class to be tested.
*/ • appletviewer is a tool that tests the applet class.

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 76
JAVA
JAVA APPLETS
APPLETS
Output

14-09-2023 14-09-2023 Dr.Maivizhi Assistant Professor


APP /Faculties
CINTEL- CINTEL 77
JAVA
JAVA APPLETS
APPLETS
Sample Applet Program-2:

package applet_ru; add(n);


import java.awt.*; add(Uname);
import java.applet.*; add(p);
public class LoginPage extends Applet add(pass);
{ add(b1);
TextField Uname,pass; add(b2);
Button b1,b2; n.setBounds(70,90,90,60);
public void init() p.setBounds(70,130,90,60);
{ Uname.setBounds(280,100,90,20);
Label n=new Label(“UserName:",Label.CENTER); pass.setBounds(200,140,90,20);
Label p=new Label("password:",Label.CENTER); b1.setBounds(100,260,70,40);
Uname=new TextField(20); b2.setBounds(180,260,70,40);
pass=new TextField(20); }
pass.setEchoChar('$'); public void paint(Graphics g)
b1=new Button("submit"); { repaint();
b2=new Button("cancel"); }
}

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 78
JAVA
JAVA APPLETS
APPLETS

Output:

14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 79
JAVA
JAVA APPLETS
APPLETS
Sample Applet Program-3

import java.applet.*; public void actionPerformed(ActionEvent e)


import java.awt.*; {
import java.awt.event.*; String temp = textField1.getText();
textField1.setText(textField2.getText());
public class AppletSample3 extends Applet textField2.setText(temp);
implements ActionListener { }
public void init() {
Label label1 = new Label("TEXT1: "); TextField textField1, textField2;
textField1 = new TextField("WELCOME"); Button swapBtn;
swapBtn = new Button("SwapButton"); }
swapBtn.addActionListener(this);
Label label2 = new Label("TEXT2: ");
textField2 = new TextField("GREETINGS!");
The above applet program is used to swap Text1 string
textField2.setEditable(false);
to Text2 and vice versa while clicking on the button
add(label1);
“SwapButton”.
add(textField1);
add(swapBtn);
add(label2);
add(textField2);
}
14-09-2023 14-09-2023 APP /Faculties
Dr.Maivizhi Assistant Professor CINTEL- CINTEL 80
JAVA
JAVA APPLETS
APPLETS
Output:

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 81
JAVA
JAVA APPLETS
APPLETS
Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used 7. public abstract boolean drawImage(Image img, int
to draw the specified string. x, int y, ImageObserver observer): is used draw the
2. public void drawRect(int x, int y, int width, int height): draws specified image.
a rectangle with the specified width and height. 8. public abstract void drawArc(int x, int y, int width,
3. public abstract void fillRect(int x, int y, int width, int height): int height, int startAngle, int arcAngle): is used draw a
is used to fill rectangle with the default color and specified circular or elliptical arc.
width and height. 9. public abstract void fillArc(int x, int y, int width, int
4. public abstract void drawOval(int x, int y, int width, int height, int startAngle, int arcAngle): is used to fill a
height): is used to draw oval with the specified width and circular or elliptical arc.
height. 10.public abstract void setColor(Color c): is used to set
5. public abstract void fillOval(int x, int y, int width, int height): the graphics current color to the specified color.
is used to fill oval with the default color and specified width and 11.public abstract void setFont(Font font): is used to
height. set the graphics current font to the specified font.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is
used to draw line between the points(x1, y1) and (x2, y2).

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 82
JAVA
JAVA APPLETS
APPLETS
Some of the AWT supplies User Interface components

• Text Fields

∙ Text area

∙ Labels

∙ Checkboxes

∙ Buttons

∙ Lists

∙ Sliders and scrollbars

∙ Drawing areas

∙ Menus

∙ Containers

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 83
JAVA
JAVA APPLETS
APPLETS
EVENT HANDLING
The pathway to efficient applet programming is how to handle events. The majority of events to which the applet will react
come from the user. The most frequent various types of events processed involve those triggered by the keyboard, mouse, and
various controllers, including push buttons. Events are supported by the java.awt.event package.
Steps to perform Event Handling
• Register the component with the Listener
• Registration Methods
• For registering the component with the Listener, many classes provide the registration methods.
For example: Button ∙public void addActionListener(ActionListener a){}

MenuItem ∙ public void addActionListener(ActionListener a){}


TextField ∙ public void addActionListener(ActionListener a){}
∙ public void addTextListener(TextListener a){}
TextArea ∙ public void addTextListener(TextListener a){}
Checkbox ∙ public void addItemListener(ItemListener a){}
Choice ∙ public void addItemListener(ItemListener a){}
List ∙ public void addActionListener(ActionListener a){}
∙ public void addItemListener(ItemListener a){}

14-09-2023 14-09-2023 APP /Faculties


Dr.Maivizhi Assistant Professor CINTEL- CINTEL 84
JAVA
JAVA APPLETS
APPLETS
Advantages of applets
• The response time is quicker because it operates on the client-side.It is secured.
• Web browsers must adhere to tight security regulations while using applets.
• It is compatible with browsers on various operating systems, including Linux, Windows, and Mac OS.

Disadvantages of applets
• The client browser requires a plugin to run the applet.
• The mobile browser on iOS or Android does not run any Java applets. Desktop browsers have dropped support
for Java applets along with the rise of mobile operating systems.

Applet features over HTML


• It displays the dynamic web pages of a web application.
• Play audio files.
• Display documents.
• Play animations.
14-09-2023 14-09-2023 APP /Faculties
Dr.Maivizhi Assistant Professor CINTEL- CINTEL 85
Java SWING - Introduction
• Swing in Java is a lightweight and
platform-independent class of the Java
foundation class. It's used to make applications
that run in windows.
• It contains elements such as a button, a scroll
bar, and a text field. A graphical user interface is
created by combining all of these elements.
• Swing Framework includes several classes that
provide more vital and more versatile GUI
(Graphical User Interface) components than
AWT(Abstract Window Toolkit).
• Swing is a Sun Microsystems-published official
Java GUI toolkit that closely resembles the look
and feels of modern Java GUIs. It is used to
create the graphical user interface for Java Class.

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 86


Java SWING FEATURES
Platform Independent
It is platform-independent, as the swing components used to construct the program are not
platform-specific. It works on any platform and in any location.
Customizable
Swing controls are simple to customize. It can be changed, and the swing component
application's visual appearance is independent of its internal representation.
Plugging
• Java Swing has pluggable look and feel. This feature allows users to change the appearance
and feel of Swing components without having to restart the application.
• The Swing library will enable components to have the same look and feel across all
platforms, regardless of where the program is running.
• The Swing library provides an API that allows complete control over the appearance and
feel of an application's graphical user interface

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 87


Java SWING FEATURES(Contd.)
• MVC stands for Model-View-Controller.
• The model agrees with the state information associated with the Component in MVC
terminology.
• The view determines how the component appears on screen and any aspects of the view
that are influenced by the model's current state.
• The controller is in charge of determining how the component responds to the user.
Manageable Look and Feel
• It's simple to manage and configure.
• Its mechanism and composition pattern allows changes to be made to the settings while
the program runs.
• Constant changes to the application code can be made without making any changes to the
user interface.

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 88


Java SWING FEATURES (Contd.)

Lightweight

• Lightweight Components: The JDK's AWT has supported lightweight component


development.
• A component must not rely on non-Java [O/s based] system classes to be
considered light.
• The look and feel classes in Java help Swing components have their view.

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 89


JFC and Swing

JFC stands for Java Foundation Classes, a set of classes used to create graphical user
interfaces (GUIs) and add rich graphical features and interactivity to Java
applications.

The Java Classes Foundation holds Java Swing (JFC).

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 90


Swing Hierarchy

JFC stands for Java Foundation


Classes, a set of classes used to
create graphical user interfaces
(GUIs) and add rich graphical
features and interactivity to Java
applications. The Java Classes
Foundation holds Java Swing
(JFC).

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 91


What are Swing Components in Java?

• A component is independent visual control, and Java Swing


Framework contains a large set of these components, providing
rich functionalities and allowing high customization.
• They all are derived from JComponent class. All these
components are lightweight components.
• This class offers some standard functionality like pluggable look
and feel, support for accessibility, drag and drop, layout, etc.
• A container holds a group of components.
• It delivers a space where a component can be managed and
displayed. Containers are of two types:

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 92


Swing Components

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 93


Top Swing components in
Jbutton Java
• JButton class to create a push button on the UI.
• The button can include some display text or images.
• It yields an event when clicked and double-clicked.
• Can implement a JButton in the application by calling one of its
constructors.
Syntax:
JButton okBtn = new JButton(“Click”);
Display:

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 94


JLabel
• Use JLabel class to render a read-only text label or images on the UI. It does not generate any
event.
Syntax:
JLabel textLabel = new JLabel(“This is 1st L...”);

• This constructor returns a label with specified text.


JLabel imgLabel = new JLabel(carIcon);
It returns a label with a car icon.

The JLabel Contains four constructors. They are as follows:


1. JLabel()
2. JLabel(String s)
3. JLabel(Icon i)
4. JLabel(String s, Icon i, int horizontalAlignment)

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 95


JTextField
The JTextField renders an editable single-line text box. Users can input non-formatted text
in the box.
Can initialize the text field by calling its constructor and passing an optional integer
parameter.
This parameter sets the box width measured by the number of columns.
Also, it does not limit the number of characters that can be input into the box.
Syntax:
JTextField txtBox = new JTextField(50);
It is the most widely used text component.
It has three constructors:
1. JTextField(int cols)
2. JTextField(String str, int cols)
3. JTextField(String str)

Note: cols represent the number of columns in the text field.


14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 96
JCheckBox

The JCheckBox renders a check-box with a label.


The check-box has two states, i.e., on and off. On selecting, the state is set to "on,"
and a small tick is displayed inside the box.
Syntax:
CheckBox chkBox = new JCheckBox(“Java Swing”, true);
• It returns a checkbox with the label Pepperoni pizza.
• Notice the second parameter in the constructor.
• It is a boolean value that denotes the default state of the check-box.
• True means the check-box defaults to the "on" state.

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 97


JRadioButton
• A radio button is a group of related buttons from which can select
only one.
• Use JRadioButton class to create a radio button in Frames and render a
group of radio buttons in the UI.
• Users can select one choice from the group.
Syntax:
JRadioButton jrb = new JRadioButton("Easy");
Display:

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 98


JComboBox
• The combo box is a combination of text fields and a drop-down list
• Use JComboBox component to create a combo box in Swing.
Syntax:
JcomboBox jcb = new JComboBox(name);

JTextArea
In Java, the Swing toolkit contains a JTextArea Class. It is under package
javax.swing.JTextArea class. It is used for displaying multiple-line text.

Declaration:
public class JTextArea extends JTextComponent

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 99


Syntax:
JTextArea textArea_area=new JTextArea("Ninja! please write something in the text area.");
The JTextArea Contains four constructors. They are as follows:
1. JTextArea()
2. JTextArea(String s)
3. JTextArea(int row, int column)
4. JTextArea(String s, int row, int column)
Display:

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 100


JPasswordField
• In Java, the Swing toolkit contains a JPasswordField Class.
• It is under package javax.swing.JPasswordField class.
• It is specifically used for the password, and we can edit them.
Declaration:
public class JPasswordField extends JTextField
Syntax:
JPasswordField password = new JPasswordField();
The JPasswordFieldContains 4 constructors. They are as follows:
• JPasswordField()
• JPasswordField(int columns)
• JPasswordField(String text)
• JPasswordField(String text, int columns)
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 101
JTable
• In Java, the Swing toolkit contains a JTable Class.
• It is under package javax.swing.JTable class.
• It is used to draw a table to display data.
Syntax:
JTable table = new JTable(table_data, table_column);
The JTable contains two constructors. They are as follows:
1. JTable()
2. JTable(Object[][] rows, Object[] columns)

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 102


JList
• In Java, the Swing toolkit contains a JList Class.
• It is under package javax.swing.JList class.
• It is used to represent a list of items together.
• We can select one or more than one items from the list.

Declaration:
public class JList extends JComponent implements Scrollable, Accessible

Syntax:
DefaultListModel<String> list1 = new DefaultListModel<>();
list1.addElement("Apple");
list1.addElement("Orange");
list1.addElement("Banan");
list1.addElement("Grape");
JList<String> list_1 = new JList<>(list1);
14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 103
The JListContains 3 constructors. They are as follows:
JList()
JList(ary[] listData)
JList(ListModel<ary> dataModel)

Display:

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 104


JOptionPane
In Java, the Swing toolkit contains a JOptionPane Class. It is under package javax.swing.JOptionPane class. It
is used for creating dialog boxes for displaying a message, confirm box, or input dialog box.
Declaration:
public class JOptionPane extends JComponent implements Accessible
Syntax:
JOptionPane.showMessageDialog(jframe_obj, "Good Morning, Evening & Night.");

The JOptionPaneContains 3 constructors. They are as following:


1. JOptionPane()
2. JOptionPane(Object message)
3. JOptionPane(Object message, intmessageType)

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 105


JScrollBar
• In Java, the Swing toolkit contains a JScrollBar class.
• It is under package javax.swing.JScrollBar class.
• It is used for adding horizontal and vertical scrollbars.
Declaration:
public class JScrollBar extends JComponent implements Adjustable, Accessible
Syntax:
JScrollBar scrollBar = new JScrollBar();

The JScrollBarContains 3 constructors. They are as following:


1. JScrollBar()
2. JScrollBar(int orientation)
3. JScrollBar(int orientation, int value, int extent, int min_, intmax_)

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 106


JMenuBar, JMenu and JMenuItem
• In Java, the Swing toolkit contains a JMenuBar, JMenu, and JMenuItem class.
• It is under package javax.swing.JMenuBar, javax.swing.JMenu and javax.swing.JMenuItem class.
• The JMenuBar class is used for displaying menubar on the frame.
• The JMenu Object is used to pull down the menu bar's components.
• The JMenuItem Object is used for adding the labeled menu item.

JMenuBar, JMenu and JMenuItem Declarations:

public class JMenuBar extends JComponent implements MenuElement, Accessible

public class JMenu extends JMenuItem implements MenuElement, Accessible

public class JMenuItem extends AbstractButton implements Accessible, MenuElement

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 107


Syntax:
JMenuBar menu_bar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menuItem1 = new JMenuItem("Never");
menuItem2 = new JMenuItem("Stop");
menuItem3 = new JMenuItem("Learing");
menu.add(menuItem1);
menu.add(menuItem2);
menu.add(menuItem3);

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 108


JPopupMenu
• In Java, the Swing toolkit contains a JPopupMenu Class.
• It is under package javax.swing.JPopupMenu class.
• It is used for creating popups dynamically on a specified position.

Declaration:
public class JPopupMenu extends JComponent implements Accessible, MenuElement
Syntax:
final JPopupMenu popupmenu1 = new JPopupMenu("Edit");

The JPopupMenuContains 2 constructors. They are as follows:


1. JPopupMenu()
2. JPopupMenu(String label)

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 109


JCheckBoxMenuItem
• In Java, the Swing toolkit contains a JCheckBoxMenuItem Class.
• It is under package javax.swing.JCheckBoxMenuItem class.
• It is used to create a checkbox on a menu.
Syntax:
JCheckBoxMenuItem item = new JCheckBoxMenuItem("Option_1");

The JCheckBoxMenuItem Contains 2 constructors. They are as following:


1. JCheckBoxMenuItem()
2. JCheckBoxMenuItem(Action a)
3. JCheckBoxMenuItem(Icon icon)
4. JCheckBoxMenuItem(String text)
5. JCheckBoxMenuItem(String text, boolean b)
6. JCheckBoxMenuItem(String text, Icon icon)
7. JCheckBoxMenuItem(String text, Icon icon, boolean b)

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 110


JSeparator
• In Java, the Swing toolkit contains a JSeparator Class.
• It is under package javax.swing.JSeparator class.
• It is used for creating a separator line between two components.
Declaration:
public class JSeparator extends JComponent implements SwingConstants, Accessible
Syntax:
jmenu_Item.addSeparator();

The JSeparatorContains 2 constructors. They are as following:


1. JSeparator()
2. JSeparator(int orientation)

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL 111


Model-View-Controller
• MVC is a blueprint for organizing code which represents one of several design patterns. To understand
the need for these patterns, think about good and bad software.
• Good software is easy to change and work with, while bad software is difficult to modify. Design
patterns help us create the good kind of software.
Software evolves over time due to various factors:
• A new feature needs to be added.
• A bug needs to be fixed.
• Software needs to be optimized.
• The software design needs to be improved.
Indicators of bad software includes:
• Rigidity – Software requires a cascade of changes when a change is made in one place.
• Fragility – Software breaks in multiple places when a change is made.
• Needless complexity – Software is overdesigned to handle any possible change.
• Needless repetition – Software contains duplicate code.
14-09-2023 Dr.Maivizhi AssistantAPP Faculties/ CINTEL
Professor - CINTEL 112
Model-View-Controller
• Software can be intentionally designed to handle changes that might occur later on.
• The best approach is to create components in the application that are loosely connected to each other.
• In a loosely coupled application, you can make a change to one component of an application without
making changes to other parts.
• There are several principles that enable reducing dependencies between different parts of an application.
• Software design patterns represent strategies for applying software design principles. MVC is one of those
patterns.
In general, a visual component is a composite of three distinct aspects:
• The way that the component looks when rendered on the screen
• The way that the component reacts to the user
• The state information associated with the component
• Throughout time, a particular architectural approach has demonstrated remarkable efficiency: namely,
the Model-View-Controller, often referred to as MVC.
14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ CINTEL
Professor - CINTEL 113
Model-View-Controller
• The Model-View-Controller (MVC) software design pattern is a method for separating concerns within a
software application.
• As the name implies, the MVC pattern has three layers:
• The Model defines the business layer of the application,
• the Controller manages the flow of the application,
• the View defines the presentation layer of the application.
Model: Handles data and business logic. Represents the business layer of the application
View: Presents the data to the user whenever asked for. Defines the presentation of the application
Controller: Entertains user requests and fetch necessary resources. Manages the flow of the application

Each of the components has a demarcated set of tasks which ensures smooth functioning of the entire
application along with complete modularity.

14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ -CINTEL
Professor CINTEL 114
Model-View-Controller
Model :
• Model is where the application’s data objects are stored. It represents knowledge as a structure of
objects.
• The model doesn’t know anything about views and controllers but it can contain logic to update
controller if its data changes.
• The model is quite simply the data for our application.
• The data is “modelled” in a way it’s easy to store, retrieve, and edit.
• The model is how we apply rules to our data, which eventually represents the concepts our
application manages.
• For any software application, everything is modelled as data that can be handled easily.
• What is a user, a book, or a message for an app? Nothing really, only data that must be processed
according to specific rules. Like, the date must not be higher than the current date, the email must be
in the correct format, the name mustn’t be more than “x” characters long, etc.
14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ CINTEL
Professor - CINTEL 115
Model-View-Controller
Model:
• Whenever a user makes any request from the controller, it contacts the appropriate model which
returns a data representation of whatever the user requested.
• This model will be the same for a particular work, irrespective of how we wish to display it to the
user.
• That is why we can choose any available view to render the model data.
• Additionally, a model also contains the logic to update the relevant controller whenever there is
any change in the model’s data.

14-09-2023 Dr.Maivizhi AssistantAPP Faculties/ CINTEL


Professor - CINTEL 116
Model-View-Controller
VIEW:
• The view determines how the component is displayed on the screen, including any aspects of the view that
are affected by the current state of the model.
• View can also update the model by sending appropriate messages. Users interact with an application through
its View.
• As the name suggests, the view is responsible for rendering the data received from the model. There may be
pre-designed templates where you can fit the data, and there may even be several different views per model
depending on the requirements.
• Any web application is structured keeping these three core components in mind. There may be a primary
controller that is responsible for receiving all the requests and calling the specific controller for specific
actions.

14-09-2023 Dr.Maivizhi AssistantAPP


Professor
Faculties/ CINTEL
- CINTEL 117
Model-View-Controller
CONTROLLER:
• The controller determines how the component reacts to the user.
• Example : When the user clicks a check box, the controller reacts by changing the model to reflect the user’s
choice (checked or unchecked).
• The controller is like housekeeper of the application – it performs coordination between model and view to
entertain a user request. The user requests are received as HTTP get or post request – for example, when the
user clicks on any GUI elements to perform any action.
• The primary function of a controller is to call and coordinate with the model to fetch any necessary resources
required to act.
• Usually, on receiving a user request, the controller calls the appropriate model for the task at hand.

14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ -CINTEL
Professor CINTEL 118
Advantages of the MVC Architecture
• A common problem faced by application developers these days is the support for different type of
devices.
• The MVC architecture solves this problem as developers can create different interfaces for different
devices, and based on from which device the request is made, the controller will select an appropriate
view.
• The model sends the same data irrespective of the device being used, which ensures a complete
consistency across all devices.
• The MVC separation beautifully isolates the view from the business logic.
• It also reduces complexities in designing large application by keeping the code and workflow structured.
• This makes the overall code much easier to maintain, test, debug, and reuse.

14-09-2023 Dr.Maivizhi AssistantAPP


Professor
Faculties/ CINTEL
- CINTEL 119
Model-View-Controller
• We are going to create a Student object acting as a model.
• StudentView will be a view class which can print student details on console
• StudentController is the controller class responsible for storing data in the Student object and updating
StudentView accordingly.
• MVCPatternDemo, our demo class, will use StudentController to demonstrate the use of MVC pattern.

14-09-2023 Dr.Maivizhi Assistant Professor / CINTEL


APP Faculties - CINTEL 120
Model-View-Controller
Step 1: Create the Model :

14-09-2023 Dr.Maivizhi AssistantAPP Faculties/ CINTEL


Professor - CINTEL 121
Model-View-Controller
Step 2: Create the View

14-09-2023 Dr.Maivizhi AssistantAPP


Professor
Faculties/ CINTEL
- CINTEL 122
Model-View-Controller
Step 3: Create the Controller
public class StudentController {
private Student model;
private StudentView view;
public StudentController(Student model, StudentView view) {
this.model = model;
this.view = view;
}
public void setStudentName(String name){
model.setName(name);
}
public String getStudentName(){
return model.getName();
}
public void setStudentRollNo(String rollNo){
model.setRollNo(rollNo);
}
public String getStudentRollNo(){
return model.getRollNo();
}
public void updateView(){
view.printStudentDetails(model.getName(), model.getRollNo());
}
}

14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ -CINTEL
Professor CINTEL 123
Model-View-Controller
Step 4: Create the main Java file

• “MVCPatternDemo.java” fetches the public class MVCPatternDemo {


public static void main(String[] args) {
student data from the database or a //fetch student record based on his roll no from the database
function (in this case we’re using a Student model = retriveStudentFromDatabase();
//Create a view : to write student details on console
function to set the values) and pushes it StudentView view = new StudentView();
StudentController controller = new StudentController(model, view);
on to the Student model. controller.updateView();
• Then, it initializes the view we had //update model data
controller.setStudentName("John");
created earlier. controller.updateView();
}
• Further, it also initializes our controller private static Student retriveStudentFromDatabase(){
and binds it to the model and the view. Student student = new Student();
student.setName("Robert");
• The updateView() method is a part of the student.setRollNo("10");
return student;
controller which updates the student }
details on the console. }

14-09-2023 Dr.Maivizhi Assistant Professor


APP Faculties/ CINTEL
- CINTEL 124
Model-View-Controller
Step 5: Test the Result

Student:
Name: Robert
Roll No: 10
Student:
Name: John
Roll No: 10

14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ CINTEL
Professor - CINTEL 125
Widgets
• Graphical User Interface (GUI) elements are the visual components that allow users to interact with
software applications.
• These elements are often referred to as "widgets," which are essentially building blocks that make up the
user interface.
• Each widget serves a specific purpose and provides a way for users to input information, view data, or
trigger actions. Here is a list of controls in the javax.swing package
Input Components
• Buttons ( JButton, JRadioButtons, JCheckBox)
• Text (JTextField, JTextArea)
• Menus (JMenuBar, JMenu, JMenuItem)
• Sliders (JSlider)
• JComboBox (uneditable) (JComboBox)
• List (Jlist )
14-09-2023 APP
Dr.Maivizhi Assistant Faculties/ CINTEL
Professor - CINTEL 126
Widgets
Information Display Components
• JLabel
• Progress bars (JProgressBar)
• Tool tips (using JComponent's setToolTipText(s) method)
Choosers
• File chooser (JFileChooser)
• Color chooser (JColorChooser)
More complex displays
• Tables (JTable)
• Trees (JTree)

14-09-2023 Dr.Maivizhi AssistantAPP


Professor
Faculties/ CINTEL
- CINTEL 127

You might also like