0% found this document useful (0 votes)
3 views

Java M4

This document provides an overview of Java applets, including their types (AWT and Swing), life cycle methods, and event handling mechanisms. It also covers JDBC for database connectivity, detailing different types of JDBC drivers and their characteristics, as well as an introduction to Java socket programming for communication between applications. Key concepts such as applet execution, event handling, and socket communication are explained with examples.

Uploaded by

nandanaparu07
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)
3 views

Java M4

This document provides an overview of Java applets, including their types (AWT and Swing), life cycle methods, and event handling mechanisms. It also covers JDBC for database connectivity, detailing different types of JDBC drivers and their characteristics, as well as an introduction to Java socket programming for communication between applications. Key concepts such as applet execution, event handling, and socket communication are explained with examples.

Uploaded by

nandanaparu07
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/ 18

󾠱

Java: Module 4
Applets
Introduction
A java applet is a small dynamic java program that can be transferred via the internet and
run by a java-compatible web browser.

All applets are sub-classes (either directly or indirectly) of Applet , and they are not stand-
alone programs.

The main difference between java-based applications and applets is that applets are
typically executed in an applet viewer or java-compatible web browser.

Types of Applets

AWT(Abstract Window Toolkit)


AWT (Abstract Window Toolkit) applets are based directly on the Applet class. These
applets use AWT to provide GUI components, such as buttons and text fields. The
AWT applet life cycle is composed of the following methods: init() , start() ,
paint(Graphics g) , stop() , and destroy() . The init() method is the first method to be

called and is used to initialize variables. The start() method is called after init()
and is used to restart an applet after it has been stopped. The paint(Graphics g)
method is called when the applet needs to be redrawn. The stop() method is called
when the applet is stopped and the destroy() method is called when the applet is
unloaded. A skeleton of an AWT applet is given below:

Java: Module 4 1
Directly based on the Applet class.

These applets use AWT to provide GUI.

Swing based

Swing applets are based on the javax.swing.JApplet class. These applets use the
Swing API to provide a more modern user interface. Swing applets have a slightly
different life cycle than AWT applets, with the following methods: init() , start() ,
stop() , destroy() , and paint(Graphics g) . The init() method is the first method to be

called and is used to initialize variables. The start() method is called after init()
and is used to restart an applet after it has been stopped. The stop() method is
called when the applet is stopped and the destroy() method is called when the applet
is unloaded. The paint(Graphics g) method is called when the applet needs to be
redrawn. A skeleton of a Swing applet is given below:

Based on the javax.swing.JApplet class.

These applets use the Swing API to provide a more modern user interface.

Life cycle of an Applet


It is important to understand the order in which the various methods shown in the
skeleton are called.

When an applet begins, the following methods are called, in this sequence:

Java: Module 4 2
: The init( ) method is the first method to be called. This is where you
init()

should initialize variables. This method is called only once during the run time of
your applet.

start() : The start( ) method is called after init( ). It is also called to restart an
applet after it has been stopped. Note that init( ) is called once i.e. when the first
time an applet is loaded whereas start( ) is called each time an applet’s HTML
document is displayed onscreen. So, if a user leaves a web page and comes
back, the applet resumes execution at start( ).

paint(Graphics g) : This method is called when the applet needs to be redrawn.


The single parameter, g, is a Graphics object that provides the applet with
methods for drawing. This method is called whenever the applet needs to be
repainted, such as when the applet is first loaded and resized

When an applet is terminated, the following sequence of method calls takes


place:

stop(): This method is called when the applet is stopped. It is used to stop the
applet's execution.

destroy() : This method is called just before the applet is unloaded. It is used to
perform any necessary cleanup tasks, such as releasing resources.

Applet Skeleton

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

//java.awt is deprecated javax.swing is the alternative

import javax.swing.JApplet;

public class AppletExample extends JApplet {

public void init() {


// initialization
}

public void start() {


// start or resume execution
}

// called when the applet is stopped


public void stop() {
// suspend execution
}

Java: Module 4 3
// This is the last method executed
public void destroy() {
// called when applet is terminated
// perform shutdown activities
}

public void paint(Graphics g) {


//redisplay the window contents
}
}

How does the java applets works ?


The Java applet works by being transferred to the user's computer via the internet. It
is then run by a Java-compatible web browser. The applet interacts with the user by
responding to user input and performing specific tasks. The applet is able to do this
by utilizing the Java language, which is a high-level programming language. The Java
language allows applets to run faster, with fewer errors, than traditional programming
languages.
When a Java applet is first loaded, the init() method is called. This method is used
to initialize variables and prepare the applet for execution. After the init() method is
called, the start() method is called. This method is used to restart the applet after it
has been stopped.
The paint(Graphics g) method is called when the applet needs to be redrawn. This
method is used to display the contents of the applet on the user's screen. When the
applet is stopped, the stop() method is called. This method is used to stop the
applet's execution. Finally, the destroy() method is called when the applet is
unloaded. This method is used to perform any necessary cleanup tasks, such as
releasing resources.

Java Event Handling


Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and
Listener interfaces for event handling.

Event types

Java: Module 4 4
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e.,
foreground events are generated due to interaction by the user on components in
Graphic User Interface (GUI). Interactions are nothing but clicking on a button,
scrolling the scroll bar, cursor moments, etc.

2. Background Events
Events that don’t require interactions of users to generate are known as
background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.

Event Handling is a mechanism to control the events and to decide what should
happen after an event occur. To handle the events, Java follows the Delegation
Event model.

Delegation Event Model

Java: Module 4 5
Source: Events are generated from the source. There are various sources like
buttons, check-boxes, list, menu-item, choice, scrollbar, text components,
windows, etc., to generate events.

Listeners: Listeners are used for handling the events generated from the
source. Each of these listeners represents interfaces that are responsible for
handling events.

To perform Event Handling, we need to register the source with the listener.

Registering the Source With Listener


Different Classes provide different registration methods.
Syntax:

addTypeListener()

where Type represents the type of event.

Example 1: For KeyEvent we use addKeyListener() to register.


Example 2:that For ActionEvent we use addActionListener() to register.

Event Classes ,interfaces and methods in Java


Event Class Listener Interface Description Methods

An event that
indicates that a
component-
defined action
ActionEvent ActionListener occurred like a actionPerformed()

button click or
selecting an
item from the
menu-item list.
The adjustment
event is emitted
AdjustmentEvent AdjustmentListener by an Adjustable adjustmentValueChanged()

object like
Scrollbar.

Java: Module 4 6
Event Class Listener Interface Description Methods

An event that
indicates that a
component componentResized()
componentShown()
ComponentEvent ComponentListener moved, the size componentMoved()
changed or componentHidden()

changed its
visibility.
When a
component is
added to a
container (or)
componentAdded()
ContainerEvent ContainerListener removed from it, componentRemoved()
then this event
is generated by
a container
object.
These are
focus-related
events, which
focusGained()
FocusEvent FocusListener include focus, focusLost()
focusin,
focusout, and
blur.
An event that
indicates
ItemEvent ItemListener whether an item itemStateChanged()

was selected or
not.
An event that
occurs due to a
keyTyped() keyPressed()
KeyEvent KeyListener sequence of keyReleased()
keypresses on
the keyboard.
The events that
occur due to the mousePressed()
mouseClicked()
user interaction
MouseEvent MouseListener mouseEntered()
with the mouse mouseExited()
mouseReleased()
(Pointing
Device).
mouseMoved()
MouseEvent MouseMotionListener mouseDragged()

Java: Module 4 7
Event Class Listener Interface Description Methods

An event that
specifies that
the mouse
MouseWheelEvent MouseWheelListener mouseWheelMoved()
wheel was
rotated in a
component.
An event that
occurs when an
TextEvent TextListener textChanged()
object’s text
changes.
An event which
windowActivated()
indicates windowDeactivated()
windowOpened()
whether a
WindowEvent WindowListener windowClosed()
window has windowClosing()
windowIconified()
changed its
windowDeiconified()
status or not.

Note: As Interfaces contains abstract methods which need to implemented by


the registered class to handle events.

Flow of Event Handling


1. User Interaction with a component is required to generate an event.

2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.

3. The newly created object is passed to the methods of the registered


listener.

4. The method executes and returns the result.

JDBC(Java Data Base Connectivity)


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 Architectural Model


Two-tier Model

Java: Module 4 8
In this model the Java applets and application are directly connected with any type of
database. The client directly communicates with database server through JDBC driver.

Three-tier Model

Java: Module 4 9
In this, there is no direct communication. Requests are sent to the middle tier i.e. HTML
browser sends a request to java application which is then further sent to the database.
Database processes the request and sends the result back to the middle tier which then
communicates with the user. It increases the performance and simplifies the application
deployment.

JDBC Drivers
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:

JDBC-ODBC bridge driver


ODBC is a standard Microsoft Windows® interface that enables communication between
database management systems and applications typically written in C or C++. JDBC is a
standard interface that enables communication between database management systems
and applications written in Oracle Java.

Java: Module 4 10
ODBC refers to the Open Database connectivity .The JDBC-ODBC bridge driver uses
ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls. This is now discouraged because of thin driver.

Advantages:

easy to use.

can be easily connected to any database.

Disadvantages:

Performance degraded because JDBC method call is converted into the ODBC
function calls.

The ODBC driver needs to be installed on the client machine.

Native-API driver (partially java driver)


The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.

Java: Module 4 11
Advantage:

performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

The Native driver needs to be installed on the each client machine.

The Vendor client library needs to be installed on client machine.

Network Protocol driver (fully java driver)


The Network Protocol driver uses middle-ware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It is fully written in
java.

Java: Module 4 12
Advantage:

No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:

Network support is required on client machine.

Requires database-specific coding to be done in the middle tier.

Maintenance of Network Protocol driver becomes costly because it requires database-


specific coding to be done in the middle tier.

Thin driver (fully java driver)


The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.

Java: Module 4 13
Advantage:

Better performance than all other drivers.

No software is required at client side or server side.

Disadvantage:

Drivers depend on the Database.

Socket Programming Socket class

Java: Module 4 14
Java Socket programming is used for communication between the applications running on
different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
The client in socket programming must know two information:

1. IP Address of Server, and

2. Port number.

Here, we are going to make one-way client and server communication. In this application, client
sends a message to the server, server reads the message and prints it. Here, two classes are
being used: Socket and ServerSocket. The Socket class is used to communicate client and
server. Through this class, we can read and write message. The ServerSocket class is used at
server-side. The accept() method of ServerSocket class blocks the console until the client is
connected. After the successful connection of client, it returns the instance of Socket at server-
side.

Java: Module 4 15
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can
be used to create a socket.

Important methods
Method Description

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.

3) public synchronized void close() closes this socket

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

Java: Module 4 16
Important methods
Method Description

returns the socket and establish a connection between server and


1) public Socket accept()
client.

2) public synchronized void


closes the server socket.
close()

Example of Java Socket Programming


Creating Server:
To create the server application, we need to create the instance of ServerSocket class. Here, we
are using 6666 port number for the communication between the client and server. You may also
choose any other port number. The accept() method waits for the client. If clients connects with
the given port number, it returns an instance of Socket.

ServerSocket ss=new ServerSocket(6666);


Socket s=ss.accept();//establishes connection and waits for the client

eg: a simple of Java socket programming where client sends a text and server receives
and prints it.

//MyServer.java

import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}

//MyClient.java

import java.io.*;
import java.net.*;

Java: Module 4 17
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}

After running the command the output will be;

Java: Module 4 18

You might also like