You are on page 1of 30

ECSECS-503: Object Oriented Techniques Unit - V Introduction to AWT :

Abstract Window Toolkit (AWT) is a set of application program interfaces (API s) used by Java programmers to create graphical user interface ( GUI ) objects, such as text fields, buttons, toggle buttons, scroll bars, windows, and menus. AWT contains several graphical widgets which can be added and positioned to the display area with a layout manager. AWT API was introduced in JDK 1.0. It contains all classes to write the program that interface between the user and different windowing toolkits. The AWT is now part of the Java Foundation Classes (JFC) the standard API for providing a graphical user interface (GUI) for a Java program. It is a portable GUI library for stand-alone applications and/or applets. A rich set of user interface components. A robust event-handling model. Graphics and imaging tools, including shape, color, and font classes. Layout managers, for flexible window layouts that don't depend on a particular window size or screen resolution. Create windows and menus for standalone Java applications.

AWT features include:

Components of AWT:
1. Container. Containers (such as Frame, Panel and Applet) are used to hold components (such as Button, Label, and TextField.) in a specific layout . Canvases. 2. Canvases. It is a simple drawing surface. Canvases are good for painting images or other graphics operation. . 3. UI component: These can include buttons, lists, simple popup menus, checkboxes, test fields and other typical elements of a user interface. 4. Window construction components: These include windows, frames, menubars, and dialogs. These are listed separately from the other User Interface components (UI components) .

Packages: AWT Packages:


AWT consists of 12 packages (Swing is even bigger, with 18 packages as of JDK 1.7). Fortunately, only 2 packages - java.awt and java.awt.event - are commonly-used. 1. The java.awt package contains the core AWT graphics classes: GUI Component classes (such as Button, TextField, and Label), GUI Container classes (such as Frame, Panel, Dialog and ScrollPane), Layout managers (such as FlowLayout, BorderLayout and GridLayout), Custom graphics classes (such as Graphics, Color and Font). 2. The java.awt.event package supports event handling: Event classes (such as ActionEvent, MouseEvent, KeyEvent and WindowEvent), Event Listener Interfaces (such as ActionListener, MouseListener, KeyListener and WindowListener), Event Listener Adapter classes (such as MouseAdapter, KeyAdapter, and WindowAdapter).

Hierarchy: AWT Class Hierarchy:


Component: Java's Abstract Windowing Toolkit provides many of the user interface objects we
find in the Windows environment. These are called "Components" of the Java AWT. Component is an abstract class that encapsulates all of the attributes of a visual component.

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 2

Basic User Interface Component (UI Component):


Label: This component is generally used to show the text or string in your application and
label never perform any type of action. Class Label has following constructors : Label(): creates an empty label with its text aligned left. Label(String): create a label with the given text string, also aligned left. Label(String, int): create a label with the given text string and the given alignment.

Label label_Name = new Label(This is label text);

Button: Button are simple UI components that trigger some action in your interface when
they are pressed. Class Button has following constructors : Button(): create an empty button with no label. Button(String): create a button with the given string object as a label.

Button button_Name = new Button(This is button label);

CheckBox: CheckBox: This component is used to create check boxes in your application. Checkboxes
have two states on and off. (or checked and unchecked or selected and unselected or true and false). Checkbox(): create an empty checkbox, unselected. Checkbox(String): create a checkbox with the given string as a label. Checkbox(String, null, Boolean): create a checkbox with the given string and given Boolean value(true/false).

Checkbox checkbox_Name = new Checkbox(Red);

Button: Radio Button: This is the special case of the Checkbox component. This is used as a
group of checkboxes which group name is same. Only one Checkbox from a Checkbox group can be selected at a time. Create an instance of CheckboxGroup class.

CheckboxGroup color = new CheckboxGroup();


Create a Checkbox instance and pass first argument value of Checkbox, second argument instance of CheckboxGroup (color), third argument ture/false.(true for selected and false for unselected).

Checkbox checkbox_Name = new Checkbox(Red, color, ture);


Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 3

Choice Choice Menus: Choice menus are popup (or pulldown) menus that enable you to select
an item from that menu. The menu then displays that choice in the screen. To create a choice menu, create an instance of the Choice class, and then use the addItem() method to add individual items to it in the order in which they should appear: Create an instance of Choice class.

Choice college=new Choice();


Add item of Choice class.

college.addItem("UIT); college.addItem("UCER); college.addItem("UIM); college.addItem("IIIT);

Text Fields: Text Fields allow you to enter any values.


TextField(): Create an empty TextField 0 characters wide. TextField(int): Create an empty text field with the given width characters. TextField(String, int): Create a text field with the give width in characters and containing the given string.

TextField comment=new TextField("Enter you facebook comment,35);

PasswordFields: PasswordFields: Password Fields allow you to enter any values and that does not echo
characters you entered. PasswordField(int): PasswordField(int): Create an empty text field with the given width characters.

PasswordField pwd = new PasswordField(25);

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 4

Layout Managers:

A layout manager is an object that controls the size and position (layout) of

components inside a Container object. For example, a window is a container that contains components such as buttons and labels.

FlowLayout - FlowLayout is the default layout manager for all Panels. It simply lays out
components from left to right in a row. If the row is full, it arranges in the next row from left to right. FlowLayout: Default FlowLayout, which centers components and leaves five pixels of space between each component. FlowLayout(int how): Create a FlowLayout with the given alignment value. FlowLayout.LEFT FlowLayout.CENTER FlowLayout.RIGHT

BorderLayout BorderLayout - BorderLayout is the default layout manager for all Windows, such as
Frames and Dialogs. It uses five areas to hold components: north, south, east, west, and center. All extra space is placed in the center area. BorderLayout() : Create a default border layout. BorderLayout( int horz, int vert): Create a border layout to specify the horizontal and vertical space left between components in horz and vert, respectively. Specify the Regions: BorderLay BorderLayout.CENTER BorderLay BorderLayout.EAST BorderLayout.WEST BorderLay BorderLay BorderLayout.NORTH BorderLay BorderLayout.SOUTH

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 5

CardLayout CardLayout are used to


produce slide shows of components, one at a time. The components are treated like a stack of cards with only one component visible at a time. CardLauout(): Creates a new card layout with gaps (pixel space between each components) of size zero. CardLayout(int horz, int vert): Creates a new card layout with the specified horizontal and vertical gaps.

GridLayout - The container is divided up into identically sized spaces. The components are
placed from top left to right going down. Unlike FlowLayout, every component gets any equal area even if they are different sizes. GridLayout() : Creates a grid layout with a default of one column per component, in a single row. GridLayout(int rows, int cols) : Creates a grid layout with the specified number of rows and columns. GridLayout(int rows, int cols, int hgap, int vgap) : Creates a grid layout with the specified number of rows and columns.

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 6

Event Handling Mechanism:


are generated by the user.

GUI applications are event-driven programs. Event handling

is at the core of successful GUI programming. Most events to which a GUI application will respond

The Delegation Event Model: The modern approach to handling events is based on the
delegation event model. A source generates an event and sends it to one or more listeners. The listener simply waits until it receives an event. Once received, the listener processes the event and then returns. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events

Event: An event is an object that describes a state change in a source. Event Source: A source is an object that generates an event. Event Listeners: A listener is an object that is notified when an event occurs. It has two
major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 7

Type of AWT EVENT


These events are used to make the application more effective and efficient. Generally, there are twelve types of event are used in Java AWT. 1. ActionEvent: It indicates the component-defined events occurred i.e. the event generated by the component like Button, Checkboxes etc. The generated event is passed to every EventListener objects. 2. AdjustmentEvent: When the Adjustable Value is changed then the event is generated. 3. FocusEvent: This class indicates about the focus where the focus has gained or lost by the object. 4. ItemEvent: The ItemEvent class handles all the indication about the selection of the object i.e. ItemEvent: whether selected or not. 5. KeyEvent: The KeyEvent class handles all the indication related to the key operation in the KeyEvent application if you press any key for any purposes of the object then the generated event gives the information about the pressed key. 6. MouseEvent: . The MouseEvent class handle all events generated during the mouse operation for the object. That contains the information whether mouse is clicked or not if clicked then checks the pressed key is left or right. 7. WindowEvent : If the window or the frame of your application is changed (Opened, closed, activated, deactivated or any other events are generated), WindowEvent is generated.

Adapter Adapter Class:

Java provides a special feature called an adapter class that can simplify

the creation of event handlers in certain situations. An adapter class provides an empty implementation of all method in an event Listener interface. Adapter class is useful when you want to receive at process only some of event that is handled by a particular event Listener interface. For example Mouse motion adapter class has two method mouse drag & mouse move. This signature of these empty methods exactly defines the mouse motion Listener interface.

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 8

Handling Steps for implementing Event Handling :


Importing package; 1) Importing java.awt.event package; event package is a subpackage of java.awt package that have Listener interfaces for all type of events, also includes their respective Adapter classes. Class. 2) Implementing Listener Interface or extending Adapter Class.

class ActionHandler implements ActionListener { public void actionPerformed(ActionEvent ae) { //Perform Task Here } }
Similarly we can implement any type of Event listener like ActionListener, MouseListener, KeyListener, WindowListener etc, or we can extend Adapter Classes like MouseAdapter, KeyAdapter, WindowAdapter etc. 3) Registering implemented Listener to event source.

Button b1 = new Button("ADD"); Button b2 = new Button("SUB"); //instantiating Event Handler ActionHandler ah = new ActionHandler(); //Registering instantiated handler to event sources. b1.addActionListener(ah); b2.addActionListener(ah);

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 9

Example : GUI Calculator

import java.awt.*; import java.awt.event.*; public class Calculator extends Frame implements ActionListener TextField t1, t2, t3; Label l1, l2, l3; Button b1, b2; public Calculator() { setSize(250,200); setVisible(true); setTitle("CALC"); setBackground(Color.GRAY); //Setting Flowlayout on Calculator Frame setLayout(new FlowLayout(FlowLayout.CENTER)); //For Window Close Operation addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) System.exit(0); }}); t1 = new TextField(20); t2 = new TextField(20); t3 = new TextField(20); b1 = new Button("ADD"); b2 = new Button("SUB"); b1.addActionListener(this); b2.addActionListener(this); l1 = new Label("Number One"); l2 = new Label("Number Two"); l3 = new Label("OPR RESULT"); {

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 10

add(l1); add(t1); add(l3); add(t3); } //End Of Constructor

add(l2); add(b1);

add(t2); add(b2);

public void actionPerformed(ActionEvent ae) { if(ae.getSource() == b1) { int n1 = Integer.parseInt(t1.getText()); int n2 = Integer.parseInt(t2.getText()); int sum = n1 + n2; t3.setText(String.valueOf(sum)); } if(ae.getSource() == b2) { int n1 = Integer.parseInt(t1.getText()); int n2 = Integer.parseInt(t2.getText()); int sum = n1 - n2; t3.setText(String.valueOf(sum)); } } //End Of Handler Method }//End Of Calculator Class class GUIDemo { public static void main(String [] ar) { Calculator c = new Calculator(); }//End Of Main Method }//End Of GUI Demo
Output : C:\United\ GUIDemo.java C:\United\CS>javac GUIDemo.java C:\United\ C:\United\CS>java GUIDemo

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 11

Swing: Swing is part of the

"Java Foundation Classes (JFC)", which was introduced in 1997 after

the release of JDK 1.1. Swing is a rich set of easy-to-use, easy-to-understand JavaBean GUI components that can be dragged and dropped as "GUI builders" in visual programming environment. Swing is now an integral part of Java since JDK 1.2. An effort to incorporate many of the features in Netscape's IFC as well as some aspects of IBM stuff First released in March of 1998 with nearly 250 classes and 80 interfaces. Advanced graphical programming. Provides assistive technology for the disabled. High quality 2D graphics and images. Pluggable look and feel supports. Drag-and-drop support between Java and native applications. Swing is not a replacement for the AWT. - Needed to support truly architecture independent interfaces - Contains more powerful components Why bother? - Increased acceptance (many more supported architectures) - AWT based on architecture-specific widgets.

Features res: Swing Features:

Pluggable Look and Feel: The Look and Feel that means the dramatically changing in the Feel: component like JFrame, JWindow, JDialog etc. for viewing it into the several type of window.

LnFs are increasingly important Similar look of underlying environment LnFs for UNIX, Windows, Apple. (Default is called Metal) LnFs can be changed at run-time

Components: Lightweight Components:


Lightweight - components which are not dependent on native source to render Heavyweights are unwieldy because: - Equivalent components may act differently on different platforms - LnF is tied to the host environment
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 12

Many new Components


Tables Trees Sliders Progress Bars Internal Frames Text Components (Very nice) Tool tips Support for undo/redo Support for Multiple Document Interfaces (MDI) with InternalFrames.

Swings Component :

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 13

AWT: Swing Vs. AWT:


S. No. 1 Point of comparison Speed Swing Swing component are generally slower and buggier than AWT, due to both the fact that they are pure java and to video issues on various platforms. 2 Applet Portability Most web browsers do not include the Most web browser support AWT swing classes, so the java plugin must be used. 3 Portability Pure java design provides for fewer platform specific limitations classes so AWT applets can run without the java plugin Use of native peers creates platform specific limitations. Some components may not function at all on some platforms. 4 Look and Feel The pluggable look and feel lets you design a single set of GUI components that can automatically have the look and feel of any OS platform. 5 Third party Development Swing development is more active. Sun puts much more energy into making swing robust. The majority of component makers, base new component development on swing components. There is a much smaller set of AWT components available, thus placing the burden in the programmer to create his or her own AWT based component. AWT component more closely reflect the look and feel of the OS they run on. AWT Use of native peers speeds component performance.

Feature

Swing supports a wider range of feature like icons and pop-up tooltips for components.

AWT components do not support feature like icons and tool-tips.

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 14

Java as an Internet Language:

Java is an object oriented language and a very simple

language. Because it has no space for complexities. At the initial stages of its development it was called as OAK. OAK was designed for handling set up boxes and devices. But later new features were added to it and it was renamed as Java. Java became a general purpose language that had many features to support it as the internet language. Few of the features that favors it to be an internet language are: Cross Platform Compatibility: The java source files (java files with .java extension) after compilation generate the bytecode (the files with .class extension) which is further converted into the machine code by the interpreter. The byte code once generated can execute on any machine having a JVM. Every operating system has it's unique Java Virtual Machine (JVM) and the Java Runtime Environment (JRE). Support to Internet Protocols: Java has a rich variety of classes that abstracts the Internet protocols like HTTP, FTP, IP, TCP-IP, SMTP, DNS etc . Support to HTML: Most of the programming languages that are used for web application uses the html pages as a view to interact with the user. Java programming languages provide its support to html. Support to Java Reflection APIs: To map the functionalities, Java Reflection APIs provides the mechanism to retrieve the values from respective fields and accordingly creates the java objects. These objects enable to invoke methods to achieve the desired functionality. Support to XML parsing: Java has JAXP-APIs to read the xml data and create the xml document using different xml parsers like DOM and SAX. These APIs provides mechanism to share data among different applications over the internet. Support to Web Services : Java has a rich variety of APIs to use xml technology in diverse applications that supports N-Tiered Enterprise applications over the internet. Features like JAXB , JAXM, JAX-RPC , JAXR etc enables to implement web services in java applications. It makes java a most suited internet language. Support to java enabled Mobile devices: Java programming language is made in such a way so that it is compatible with mobile devices also. Java language also works with any java enabled mobile devices that support MIDP 1.0/2.0 including the Symbian OS mobile devices.

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 15

Java Database Connectivity (JDBC) :


JDBC is a standard or open application programming interface (API) for accessing a database from JAVA programs. The JDBC API define interface & classes for writing database application in java by making database connection.

Features or Advantage of JDBC: Using JDBC you can send SQL and PL/SQL query to
database. JDBC is a java API for executing SQL statement and support basic SQL functionality.

JDBC Architecture : The JDBC API supports both two-tier and three-tier processing
models for database access.

1. Java code calls JDBC library 2. JDBC loads a driver 3. Driver talks to a particular database 4. Can have more than one driver -> more than one database 5. Ideal: can change database engines without changing any application code

Type of Drivers: Type 1 JDBC Driver


JDBCJDBC-ODBC Bridge driver Type 1 drivers are "bridge" drivers. They use another technology such as Open Database Connectivity (ODBC) to communicate with a database. This is an advantage because ODBC drivers
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 16

exist for many Relational Database Management System (RDBMS) platforms. Type 1 driver needs to have the bridge driver installed and configured before JDBC can be used with it. These drivers are also known as JDBC ODBC Bridge Driver. Advantage The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available. Disadvantages
1. 2. 3. 4.

Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable. They are the slowest of all driver types. The client system requires the ODBC Installation to use the driver. Not good for the Web.

Type 2 JDBC Driver


NativeNative-API/partly Java driver Type 2 drivers use a native API to communicate with a database system. Java native methods are used to invoke the API functions that perform database operations. Type 2 drivers are generally faster than Type 1 drivers. Advantage Better performance than Type 1 since no jdbc to odbc translation is needed. Disadvantage 1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet. 2. If we change the Database we have to change the native API as it is specific to a database. 3. Usually not thread safe.

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 17

Type 3 JDBC Driver


Java/NetAll Java/Net-protocol driver These drivers use middleware to communicate with a server. The server then translates the protocol to DBMS function calls specific to DBMS. Type 3 JDBC drivers are the most flexible JDBC solution because they do not require any native binary code on the client. Advantage 1. This driver is server-based, so there is no need for any vendor database library to be present on client machines. 2. This driver is very flexible allows access to multiple databases using one driver. Disadvantage It requires another server application to install and maintain. Traversing the record set may take longer, since the data comes through the backend server.

Type 4 JDBC Driver


Native-protocol/allNative-protocol/all-Java driver The Type 4 uses java networking libraries to communicate directly with the database server. They are also written in 100% java and move efficient among all driver types. Advantage 1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web. Disadvantage With type 4 drivers, the user needs a different driver for each database.
Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 18

Steps of connectivity a JAVA application to Database: Database:


Loading Driver Establishing Connection Executing Statements Getting Results Closing Database Connection

1. Loading Driver: In this step of the jdbc connection process, we load the driver class by calling Class.forName(String DriverClassName) with the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. Syntax:

try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Or any other driver } catch(ClassNotFoundException e) { System.out.println( Unable to load the driver class! ); }
2. Establishing Connection: JDBC URL Syntax: jdbc: <subprotocol>: <subname> Each subprotocol has its own syntax for the source. Were using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver. The getConnection(String url, String username, String password) is a static method of getConnection(String password) DriverManager class. Which return a Connection class object. Syntax :

try{ Connection con=DriverManager.getConnection("jdbc:odbc:vijayDB",,); } catch( SQLException e ) { System.out.println( Couldnt get connection! ); }


Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 19

3. Creating a jdbc Statement object: Once a connection is obtained we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. To execute SQL statements, you need to instantiate a Statement object from your connection object by using the createStatement() method. Syntax:

Statement statement = con.createStatement(); //con Connection Object


4. Getting Result: Statement interface defines methods that are used to interact with database via the execution of SQL statements. The Statement has following methods for executing SQL statements: executeQuery(), and executeUpdate() For a SELECT statement, the method to use is executeQuery() that returns java.sql.ResultSet object that holds the fetched data from your select query. For statements that create or modify tables, the method to use is executeUpdate() that returns int that represents the number of rows affected by your query. ResultSet: ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. (employee is table name) Syntax: ResultSet rs=st.executeQuery("SELECT * FROM employee);

ResultSet: Looping the ResultSet: The next() method is used to successively step through the rows of the tabular results. Syntax: rs.next(); // rs instance of ResultSet;

5. Closing and Commiting Transaction : After task completion we should commit the transaction and then close the connection. Connection object provide two methods for performing these two tasks. Syntax:

con.commit(); // con is Connection class Object; con.close();


Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 20

JAVA application with MS Access Connectivity: Java Class : JDBCDemo.java


import java.sql.*; class JDBCDemo { public static void main(String [] ar) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:united","",""); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("Select *from Student"); System.out.printf("+--------+--------------+--------+\n"); System.out.printf("|%-8s|%-14s|%-8s|","Roll No","Student Name","Branch"); System.out.printf("\n+--------+--------------+--------+"); while(rs.next()) { System.out.println(); System.out.printf("|%-8s|",rs.getString(1)); System.out.printf("%-14s|",rs.getString(2)); System.out.printf("%-8s|",rs.getString(3)); } System.out.printf("\n+--------+--------------+--------+\n"); con.close(); } //End Of Main Method }// End Of JDBCDemo class

MS Access Database : College.mdb

Database name : College and Table name : Student o

OUTPUT :

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 21

APPLET LET: Introduction to APPLET:


What is an Applet ? Java applet are compiled java class files that are run on a page within a Web browser. Applet are small java program that are primary used in internet computing. They can be transported over the internet from one computer to another and run using the Applet Viewer or any web browser that support java.

Types of Applet : Applets are mainly categories into two types : Local Applet : The applets that are available on a machine and are tested and run on same

machine are called local applets.


Remote Applet : The applets that are available on a machine and are tested and run on remote

machine using its address or URL are called remote applets.


Creating a Simple Applet : Applet begins with two import statements. The first imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user through the AWT. The AWT contains support for a window-based, graphical interface. The second import statement imports the applet package, which contains the class Applet Every applet that you create must be a subclass of Applet. Applet. Applet.

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 22

Developing Simple Applet : FirstApplet.java

import java.applet.*; import java.awt.*; /* <applet code = FirstApplet.class </applet> */

width = 200

height=200>

public class FirstApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello World..!!!",25,50); } }

Compiling and Running Applet :

Compile : javac FirstApplet.java Run :


There are two ways in which you can run an applet: Executing the applet within a Java-compatible Web browser. Using an applet viewer, such as the standard SDK tool, appletviewer An appletviewer. applet viewer executes our applet in a window. This is generally the fastest and easiest way to test our applet.

appletviewer FirstApplet.java or appletviewer TestApplet.html or Run TestApplet.html page using web browser

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 23

Methods Of Applet Class : Applet class provides all necessary support for applet execution, such as starting and stopping. It also provides methods that load and display images, and methods that load and play audio clips. Panel. Container, Applet extends the AWT class Panel In turn, Panel extends Container which extends Component. Component These classes provide support for Javas window-based, graphical interface. Thus, Applet provides all of the necessary support for window-based activities. public void init() - Called when an applet begins execution. It is the first method called for

any applet.
public void start() - Called by the browser when an applet should start (or resume)

execution. It is automatically called after init( ) when an applet first begins.


public void stop() - Called by the browser to suspend execution of the applet. Once stopped,

an applet is restarted when the browser calls start( ). )


public void destroy() - Called by the browser just before an applet is terminated. Your applet

will override this method if it needs to perform any cleanup prior to its destruction.
public void paint(Graphics g) - The paint( ) method is called each time your applets output

must be redrawn.

Life Cycle Of Applet :

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 24

The Paint Method :


Our applet has a method to paint some colored graphics like lines, circles, rectangles etc on the applet screen. public void paint(Graphics g) { } public says that anyone can use this method void says that it does not return a result paint is the name of the method Method names should begin with a lowercase letter The argument, or parameter (theres only one) is inside parentheses that is a reference of Graphics class of awt package. A Graphics is an object that holds information about a painting It remembers what color you are using It remembers what font you are using You can paint on it (but it doesnt remember what you have painted) Methods Of Graphics Class : drawString(String text, int x, int y) drawString drawLine( drawLine int startX, int startY, int endX, int endY) drawRect(int top, int left, int width, int height) drawRect fillRect(int top, int left, int width, int height) fillRect drawRoundRect(int top, int left, int width, int height,int arcwidth, int archeight) RoundRect drawRoundRect fillRoundRect(int top, int left, int width, int height, int arcwidth, int archeight) fillRoundRect Rect drawOval(int top, int left, int width, int height) drawOval fillOval(int top, int left, int width, int height) fillOval drawArc drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) Arc fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) fillArc

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 25

SERVLET: Introduction to SERVLET:


Servlets are server side Java classes that add functionality to a web server in a manner similar to the way applets add functionality to a browser. Servlets can be used as a replacement for CGI scripts (or ASP scripts) and they support the standard request/response protocol supported by web servers. In this request/response protocol, a client sends a request message to a server and the server responds by sending back a reply message Reply is usually as HTML Could be image, audio stream, video stream, etc. Servlets classes generally implements either the Servlet interface or extend the HttpServlet abstract class Servlet runs on J2EE servers web container that is servlet container (Tomcat is a popular one) Servlets are platform independent Servlets are generally invoked from a hyperlink or from the action attribute of an HTML form. The Servelt API : Two packages contain the classes and interfaces that are required to build servlets. These are javax.servlet.http. javax.servlet and javax.servlet.http they are not included in the Java Software Development Kit. You must download J2EE web server to obtain their functionality.

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 26

The Servlet Interface : All servlets must implement the Servlet interface. It declares the init( ) service( ) and ), ), destroy() destroy() methods that are called by the server during the life cycle of a servlet.

Developing Simple Servlet : STEP 1: Create and compile source code of Servlet : FirstServlet.java

import javax.servlet.*; public class FirstServlet implements Servlet { public void init(ServletConfig) { //Code Here For Initialization } public void service(ServletRequest req, ServletResponse res) throws IOException, ServletExcepion { PrintWriter out = res.getWriter(); out.println("<B>Hello World!!!</B>"); out.println("<BR>"); out.println("This is my first J2EE Web Application using Servlet."); out.close(); }

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 27

public void destroy() { //Code Here That is required when Servlet Object unload from container. } public String getServletInfo() { return "This is my First Servelt"; } public ServletConfig getServletConfig() { return null; } }//End Of FirstServlet class.

STEP 2: Start Tomcat and Deploy FirstServlet on server.

Open Tomcat configuration window from Program menu and then start tomcat or run startup.bat from the Tomcat installation directory.
STEP 3: Start Web Browser and request the FirstServlet Start a Web browser and enter the URL shown here:

http://localhost:8080/MyWebApp/FirstServlet
we can also write 127.0.0.1 in place of localhost.

http://127.0.0.1:8080/ MyWebApp/FirstServlet

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 28

Servlet Life Cycle:


init() - This method is called when a servlet is first invoked by the servlet container. It could be used to write code that initializes files or connections to databases. service() - This method process requests from the client (for example, a hyperlink or form action). It returns a response (usually HTML) back to the client. The service() method provides two parameters: ServletRequest and ServletResponse to provide access to the request object and response object destroy() - Called just before servlet is destroyed by container to enable programmer to clean up any resources (e.g. close a db connection).

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 29

Difference Difference between Servlet and CGI :


S.No. 1 2 3 Servlet Servlets can link directly to the Web server. Servlets can share data among each other. Servlets can perform session tracking and caching of previous computations. 4 5 Servlets are portable. In Servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread.process. 6 Servlets automatically parse and decode the HTML form data. 7 Servlets can read and set HTTP headers, handle cookies, tracking sessions. 8 9 Servlets is inexpensive than CGI. Servlet build with java CGI cannot automatically parse and decode the HTML form data. CGI cannot read and set HTTP headers, handle cookies, tracking sessions. CGI is more expensive than Servlets. CGI Build with scripting languages. (like C, C++, Perl etc) CGI (Common Gateway Interface) CGI cannot directly link to Web server. CGI does not provide sharing property. CGI cannot perform session tracking and caching of previous computations. CGI is not portable. In CGI, each request is handled by a heavyweight operating system

Content Developed by : Mr. Faiz Mohd Arif Khan and Harish Kumar 30

You might also like