0% found this document useful (0 votes)
145 views19 pages

Applets: Unit - V

The document discusses several topics related to Java programming: 1. Applets - including their definition, advantages, differences from applications, lifecycle states, and the basic structure of an applet class. 2. GUI programming with Swing - including components, containers, layout managers, and event handling. 3. Accessing databases with JDBC - including driver types, architecture, classes/interfaces, and basic steps to develop JDBC applications. The document provides code examples for a basic "Hello World" style applet and discusses how to request repainting by calling the repaint() method instead of directly calling paint().

Uploaded by

dil rock
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
145 views19 pages

Applets: Unit - V

The document discusses several topics related to Java programming: 1. Applets - including their definition, advantages, differences from applications, lifecycle states, and the basic structure of an applet class. 2. GUI programming with Swing - including components, containers, layout managers, and event handling. 3. Accessing databases with JDBC - including driver types, architecture, classes/interfaces, and basic steps to develop JDBC applications. The document provides code examples for a basic "Hello World" style applet and discusses how to request repainting by calling the repaint() method instead of directly calling paint().

Uploaded by

dil rock
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

JAVA UNIT-5

UNIT – V
Applet: Basics, Architecture, Applet Skeleton, requesting repainting, using the status
window, passing parameters to applets

GUI Programming with Swings – The origin and design philosophy of swing, components
and containers, layout managers, event handling, using a push button, jtextfield, jlabel
and image icon, the swing buttons, jtext field, jscrollpane, jlist, jcombobox, trees, jtable,
An overview of jmenubar, jmenu and jmenuitem, creating a main menu,
showmessagedialog, showconfirmdialog, showinputdialog, showoptiondialog, jdialog,
create a modeless dialog.

Accessing Databases with JDBC: Types of Drivers, JDBC Architecture, JDBC classes and
Interfaces, Basic steps in developing JDBC applications, Creating a new database and table
with JDBC.

--------------------------------------------------------------------------------------------------------

APPLETS
5.11.Introduction:

Applet – Definition:

Applets are small applications that are accessed on an Internet server,


transported over the Internet, automatically installed, and run as part of a web
document.
An applet is a Java program that runs in a Web browser.
Applets are designed to be embedded within an HTML page to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many platforms,
including Linux, Windows, Mac Os etc.
Differences between Applets and Applications

FEATURE APPLICATION APPLET

main()
Present Not present
metho

Page 1
JAVA UNIT-5

d
Requires a java enables web
browser like Chrome, Netscape
Execution Requires JRE
Navigator, Opera, HotJava and so
on.

Called as stand-alone
Requires some third party tool help
Nature application as application
like a browser to execute
can be executed from
command prompt.
Can access any data or cannot access anything on the
Restrictions
software available on the system except browser’s services.
system

GUI GUI is incorporated explicitly GUI is readily available.

HTML No HTML file is required HTML file is required

Requires highest security for the


Security Does not require any
system as they are untrusted
security
5.1.2. Applet Lifecycle or Applet Skeleton

Every applet is in one of the following states during it’s lifetime.


1. Born State.
2. Running State
3. Idle State
4. Dead State
The following figure shows the lifecycle of an applet.

Page 2
JAVA UNIT-5

Four methods in the Applet class of java.applet package gives us the framework
to build an applet.
1. init( )
2. start( )
3. stop( )
4. destroy( )
1. New Born State: (Initialization State)
 Applet enters to this state when it is first loaded by calling init() method.
 In this stage, we will do the following:
1. Create objects needed by applet
2. Setup initial values
3. Load images and fonts
4. Setup colors.
 We should override init( ) method as follows:
 publi void init( ) {...................}
 This method is called only once during the lifetime of the applet.
2. Runnning State
 Applet enters this state when the system calls start( ) method.
 It calls automatically, once the applet is initialized.
 It also moves an idle applet to running state.
 If required, this method can be overrided as
follows: public void start( )
{
----------// @override@ ------------
}
3. Idle or Stopped State
 An applet becomes idle when it is stopped from running.
 Stopping occurs automatically when we leave the page containing the
currently running applet then stop( ) method is invoked.
 If required, this method can be overrided as
follows: public void stop( )
{
----------// @override@ ------------
}
4. Dead State
 An applet is said to be dead, when it is removed from memory.
 It occurs automatically by invoking the destroy( ) method when we
quit the browser.
 If required, this method can be overrided as
follows: public void destroy( )

Page 3
JAVA UNIT-5

{
----------// @override@ ------------
}

5. Display State
 Applet moves to this state whenever it has to perform some output
operations on the screen.
 The paint( ) is called to display.
 It is called after the applet enter into the running state.
 Every applet will have a paint( ) method and it must be overrided as
follows: public void paint(Graphics g)
{
----------// @override@ ------------
}
 The paint( ) method takes one parameter of type Graphics and it
contains graphics context.

5.1.3.Applet Class/ Architecture


 Every applet is a sub class of Applet class of java. applet package, hence
to design an applet, Applet class must be extended.
 Following figure shows the chain of classes inherited by Applet class.

Building an Applet Code


Applet code uses the services of two classes: Applet and Graphics class of java.applet

and java.awt package respectively. Hence they must be imported.


General Format:
import java.applet.Applet;

Page 4
JAVA UNIT-5

import java.awt.Graphics;

public class ClassNameApplet extends Applet {

public void paint(Graphics g)

{
----------------------------------------
----------------------------------------

}
}
Executing an Applet
Two ways: 1. Using Web Browser
2. Using appletviewer command
1. Using Web Browser
-- Build applet code (.java file)
-- Compile applet code (.class file)
-- create HTML file (.html file)

<HTML>
<applet code = ".class file" height = 100 width = 150>
</applet>
</HTML>
2. Using appletviewer command
 To view and test an applet more conveniently during development
stage, we can use appletviewer command at command prompt.
 Simply include a comment at the head of the java sourcefile that contains
the
<APPLET> tag.
/* <HTML>

<applet code=".class file" height=100 width=150>

</applet>

</HTML> */

Program: Develop an applet that displays a simple message.


Source Code:
import java.applet.Applet;

import java.awt.Graphics;

Page 5
JAVA UNIT-5

/* <HTML>
<Applet code="Message.class" height=100 width=150>
</Applet>
</HTML> */

public class Message extends Applet {

public void paint(Graphics g)

{
g.drawString("welcome to applets",10,100);
}
}

Output:
At command prompt

E:\sudheer> javac Message.java


E:\sudheer> appletviewer
Message.java

5.1.4. Requesting Repainting

An applet writes to its window only when its update( ) or paint( ) method is
called by the AWT.
How can the applet itself cause its window to be updated when its information

Page 6
JAVA UNIT-5

changes? The paint() method is called by the JVM implicitly in two


circumstances.
 When the first time frame is created and displayed.
 When the frame is resized (by dragging the frame border with mouse)
by the user.
If the programmer would like to call the paint( ) method in the middle of the
coding, it is permitted to call repaint() method and not permitted to call
paint( ) method directly.
What is the designing secret in not allowing paint() to call directly?
Calling paint( ) method raises compilation error. Before the window is
to be drawn with new data, the old data must be erased, else, both overwrite
the other and finally the data is not readable. This automatic erasing is done by
the repaint() method. repaint(): The repaint() method calls automatically
update() method and in turn the
update() method calls paint() method.
The repaint( ) method is defined by the AWT. Thus, to update an applet, simply
store the output and then call repaint( ).
The repaint( ) method has four forms.

 void repaint( ); causes the entire window to be repainted.


 void repaint(int left, int top, int width, int height); causes the specified
region will be repainted.
Here, left and top- the coordinates of the upper-left corner of
the region width and height of the region are passed in
width and height.
 void repaint(long maxDelay);
 void repaint(long maxDelay, int x, int y, int width, int height);
Here, maxDelay specifies the maximum number of milliseconds that
can elapse before update( ) is called.

Program: Write a java program to design a simple moving banner applet.

import java.awt.*;
import java.applet.Applet;
import java.awt.Graphics;

Page 7
JAVA UNIT-5

/*
<applet code=" RepaintDemo " width=300 height=50>
</applet>
*/
// class extending
public class RepaintDemo extends Applet 

{
int test=2;
public void paint(Graphics graphics)
{
super.paint(graphics);
setBackground(Color.cyan);   // set backgroung color of window
graphics.setColor(Color.black);   // set color of Text appearing on window
graphics.drawString("Value of Variable test = "+test, 80, 80);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex){}
// increasing value of variable by 1 and update its value of GUI
test++;
repaint();
}
}
Output:

At command prompt

E:\> javac RepaintDemo.java

E:\> appletviewer RepaintDemo.java

Page 8
JAVA UNIT-5

In the above example an applet and a variable called test is declared inside it.
We are continuously incrementing value of variable test and we want to ensure that
updated value of variable is visible on user interface. Therefore we are making use of
repaint method that ensures to call update method before paint method. Output of the
above program. In this window value of test variable is always incrementing and
updated value is visible on GUI.

5.1.5. Using the Status Window

An applet can also output a message to the status window of the


browser or applet viewer on which it is running.
It is required to call showStatus( ) with the string that you want displayed in a
status window.
The status window is a good place to
 Give the user feedback about what is occurring in the applet
 Suggest options
 Possibly report some types of errors
Program: Write a java program to demonstrate the status window of an applet.
import java.awt.*;

import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
public class StatusWindow extends Applet{
public void init() {
setBackground(Color.cyan);
}
// Display msg in applet window. public void paint(Graphics g) {
g.drawString("This is in the applet window.",10, 20);
showStatus("This is shown in the status window.");
}
}

Page 9
JAVA UNIT-5

Output:At command prompt

5.1.6. Passing parameters to applets


To get any information from the HTML file as a parameter. For this purpose,
Applet class provides a method named getParameter().

Syntax:
public String getParameter(String parameterName)  

Example of using parameter in Applet:


import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/

Page 10
JAVA UNIT-5

Output:

Accessing Databases with JDBC:

 Java Database Connectivity (JDBC) is an Application Programming Interface


(API) used to connect Java application with Database.

 JDBC is used to interact with various type of Database such as Oracle, MS Access,
My SQL and SQL Server.

 The JDBC API consists of classes and methods that are used to perform various
operations like: connect, read, write and store data in the database.
 
How JDBC connect Java Application to the database by following image.

JDBC Driver
 JDBC Driver is required to establish connection between application and
database. It also helps to process SQL requests and generating result.
Types of driver

Page 11
JAVA UNIT-5

Type-1 Driver or JDBC-ODBC bridge


Type-2 Driver or Native API Partly Java Driver
Type-3 Driver or Network Protocol Driver
Type-4 Driver or Thin Driver

JDBC-ODBC Bridge:
 Type-1 Driver acts as a bridge between JDBC and other database connectivity
mechanism (ODBC).
 This driver converts JDBC calls into ODBC calls and redirects the request to the
ODBC driver.
Note: In Java 8, the JDBC-ODBC Bridge has been removed.

Advantage
 Easy to use
 Allow easy connectivity to all database supported by the ODBC Driver.
Disadvantage
 Slow execution time
 Dependent on ODBC Driver.
 Uses Java Native Interface(JNI) to make ODBC call.

Native API Driver


 This type of driver make use of Java Native Interface(JNI) call on database
specific native client API.
 These native client API are usually written in C and C++.

Page 12
JAVA UNIT-5

Advantage
 faster as compared to Type-1 Driver
 Contains additional features.
Disadvantage
 Requires native library
 Increased cost of Application

Network Protocol Driver


 This driver translates the JDBC calls into a database server independent and
Middleware server-specific calls.
 Middleware server further translates JDBC calls into database specific calls.

Advantage
 Does not require any native library to be installed.
 Database Independency.
 Provide facility to switch over from one database to another database.
Disadvantage
 Slow due to increase number of network call.

Page 13
JAVA UNIT-5

Thin Driver
 This is Driver called Pure Java Driver because. This driver interact directly with
database.
 It does not require any native database library, that is why it is also known as
Thin Driver.

Advantage
 Does not require any native library.
 Does not require any Middleware server.
 Better Performance than other driver.
Disadvantage
 Slow due to increase number of network call.
JDBC Architecture

 JDBC Application Layer


JDBC Application Layer consists of two components - Java application and JDBC
API. In Application layer, a java Application that wishes to communicate with a
database uses the JDBC API to access the required JDBC driver. The JDBC API contains
the JDBC driver manager, which connects Java application with the JDBC driver. Please
refer to Figure - 1.

Page 14
JAVA UNIT-5

JDBC Driver Layer


JDBC Driver Layer consists of several database drivers that may be required to
connect a Java application to its choice of a specific database. For example - the JDBC
Driver Layer may contain a MySQL database driver, an Oracle driver and a MariaDB
Database driver to connect any Java application with any of these databases as per the
requirement of this Java application.

This JDBC driver translates the requests of a Java application such a database
query like database access, update or storing procedures from Java language to
Structured Query Language(SQL), which is then forwarded to a specific database of
choice of this Java application.

These SQL statements are executed by the preferred database and the result is
sent back to JDBC driver. The JDBC driver sends the result back to Java
application(through JDBC API) in the form which it can easily understand. Please refer
to Figure - 1.

JDBC classes and interface

JDBC classes and interface required to connect a Java application to a database are -

Driver interface - A Java application can access a database through its driver. Driver
interface represents the database driver that is used to establish the connectivity of a
Java application with the database.

DriverManager class - DriverManager class is used to load and register the driver of


any particular database in order to connect a Java application to this database.

Connection interface - It enables a Java application to connect to a database.

Statement interface - It enables a Java application to execute Structured Query


Language (SQL) statements in order to perform database operations.

ResultSet interface - It represents a set of data stored in a table, which is the result of


executing SQL statements to retrieve the data from the database.

SQLException class - It represents an exception raised which interrupted the


connection between the Java application and the database.

Page 15
JAVA UNIT-5

Steps to connect a Java Application to Database


The following 5 steps are the basic steps involve in connecting a Java application with
Database using JDBC.
1. Register the Driver
2. Create a Connection
3. Create SQL Statement
4. Execute SQL Statement
5. Closing the connection

1. Register the Driver

 It is first an essential part to create JDBC connection.


 JDBC API provides a method Class.forName() which is used to load the driver
class explicitly.
 For example, if we want to load a jdbc-odbc driver then the we call it like
following.

Example to register with JDBC-ODBC Driver

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

2. Create a Connection
 After registering and loading the driver in step1, now we will create a
connection using getConnection() method of DriverManager class.
 This method has several overloaded methods that can be used based on the
requirement.
 Basically it require the database name, username and password to establish
connection. Syntax of this method is given below.
Syntax

Page 16
JAVA UNIT-5

getConnection(String url)
getConnection(String url, String username, String password)
getConnection(String url, Properties info)

This is a sample example to establish connection with Oracle Driver

Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"username","password"
);

3. Create SQL Statement


 In this step we will create statement object using createStatement() method.
 It is used to execute the sql queries and defined in Connection class.
Syntax
public Statement createStatement() throws SQLException
Example to create a SQL statement:
Statement s=con.createStatement();
4. Execute SQL Statement
 After creating statement, now execute using executeQuery() method of
Statement interface.
 This method is used to execute SQL statements.
Syntax
public ResultSet executeQuery(String query) throws SQLException

Example to execute a SQL statement


In this example, we are executing a sql query to select all the records from the
user table and stored into resultset that further is used to display the records.

ResultSet rs=s.executeQuery("select * from user");


while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getString(2));
}

5. Closing the connection


 This is final step which includes closing all the connection that we opened in our
previous steps.
 After executing SQL statement you need to close the connection and release the
session.
 The close() method of Connection interface is used to close the connection.
Syntax

Page 17
JAVA UNIT-5

public void close() throws SQLException


Example of closing a connection
con.close();

Now lets combine all these steps into a single example and create a complete
example of JDBC connectivity.
Example: All Steps into one place
import java.sql.*;
class Test {
public static void main(String[] args) {
try {
//Loading driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//creating connection
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"username", "password");
Statement s = con.createStatement(); //creating statement
ResultSet rs = s.executeQuery("select * from Student"); //executing statement
while (rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2));
}
con.close(); //closing connection
} catch (Exception e) {
e.printStacktrace();
}
}
}
CREATE a table with JDBC

Java Database Connectivity(JDBC) API provide a set of classes and interfaces


that allow a Java application to connect to a database and execute SQL statements such
as -
 Creating a table.
 Inserting the data in the database.
 Retrieving the data from the database.
 Updating the data in the database.

// How to create a table using JDBC API


import java.sql.*;
class A
{
public static void main(String... ar)
{

Page 18
JAVA UNIT-5

try
{
//SQL CREATE TABLE query
String query = "CREATE TABLE MyTable (" + "ID int," + "FirstName
varchar(30)," + "LastName varchar(30)," + "Age int )";

//Loading and registering Oracle database thin driver


Class.forName("oracle.jdbc.driver.OracleDriver");

//Creating a connection between Java program and Oracle database.


Connection con = DriverManager.getConnection("jdbc:oracle:thin:
@localhost:1521:XE","scott", "tiger");

//Creating a Statement object to excute SQL statements


Statement stmt = con.createStatement();

//Executing a SQL query using Statement object.


int count = stmt.executeUpdate(query);

System.out.println("Total rows updated "+ count);


}
catch(Exception e)
{
System.out.println(e);
}
} //main method() ends

} //class definition ends

Output:

Page 19

You might also like