Sunteți pe pagina 1din 155

Java/J2EE

06CS753
JAVA AND J2EE

UNIT - 1

TS
.IN

INTRODUCTION TO JAVA: Java and Java applications; Java Development Kit (JDK);
Java is interpreted, Byte Code, JVM; Object-oriented programming; Simple Java
programs. Data types and other tokens: Boolean variables, int, long, char, operators,
arrays, white spaces, literals, assigning values; Creating and destroying objects; Access
specifiers. Operators and Expressions: Arithmetic Operators, Bitwise operators,
Relational operators, The Assignment Operator, The? Operator; Operator Precedence;
Logical expression; Type casting; Strings Control Statements: Selection statements,
iteration statements, Jump Statements.
6 Hours
UNIT - 2

UNIT - 3

TU
D

EN

CLASSES, INHERITANCE, EXCEPTIONS, APPLETS: Classes: Classes in Java;


Declaring a class; Class name; Super classes; Constructors; Creating instances of class;
Inner classes. Inheritance: Simple, multiple, and multilevel inheritance; Overriding,
overloading. Exception handling: Exception handling in Java. The Applet Class: Two
types of Applets; Applet basics; Applet Architecture; An Applet skeleton; Simple Applet
display methods; Requesting repainting; Using the Status Window; The HTML APPLET
tag; Passing parameters to Applets; getDocumentbase() and getCodebase(); ApletContext
and showDocument(); The AudioClip Interface; The AppletStub Interface; Output to the
Console.
6 Hours

CI

TS

MULTI THREADED PROGRAMMING, EVENT HANDLING: Multi Threaded


Programming: What are threads? How to make the classes threadable; Extending
threads; Implementing runnable; Synchronization; Changing state of the thread;
Bounded buffer problems, read-write problem, producer-consumer problems. Event
Handling: Two event handling mechanisms; The delegation event model; Event classes;
Sources of events; Event listener interfaces; Using the delegation event model; Adapter
classes; Inner classes.
7 Hours

UNIT - 4
SWINGS: Swings: The origins of Swing; Two key Swing features; Components and
Containers; The Swing Packages; A simple Swing Application; Create a Swing Applet;
Jlabel and ImageIcon; JTextField;The Swing Buttons; JTabbedpane; JScrollPane; JList;
JComboBox; JTable.
7 Hours

CITSTUDENTS.IN

Page 1

Java/J2EE

06CS753

PART - B
UNIT - 5

TS
.IN

JAVA 2 ENTERPRISE EDITION OVERVIEW, DATABASE ACCESS: Overview of


J2EE and J2SE. The Concept of JDBC; JDBC Driver Types; JDBC Packages; A Brief
Overview of the JDBC process; Database Connection; Associating the JDBC/ODBC
Bridge with the Database; Statement Objects; ResultSet; Transaction Processing;
Metadata, Data types; Exceptions.
6 Hours

EN

UNIT - 6
SERVLETS: Background; The Life Cycle of a Servlet; Using Tomcat for Servlet
Development; A simple Servlet; The Servlet API; The Javax.servlet Package; Reading
Servlet Parameter; The Javax.servlet.http package; Handling HTTP Requests and
Responses; Using Cookies; Session Tracking.
7 Hours
UNIT - 7

UNIT - 8

TU
D

JSP, RMI: Java Server Pages (JSP): JSP, JSP Tags, Tomcat, Request String, User Sessions,
Cookies, Session Objects. Java Remote Method Invocation: Remote Method Invocation
concept; Server side, Client side.
6 Hours

TS

ENTERPRISE JAVA BEANS: Enterprise java Beans; Deployment Descriptors; Session


Java Bean, Entity Java Bean; Message-Driven Bean; The JAR File.
7 Hours
TEXT BOOKS:

CI

1. Java - The Complete Reference Herbert Schildt, 7th Edition, Tata McGraw Hill,
2007.
2. J2EE - The Complete Reference Jim Keogh, Tata McGraw Hill, 2007.

REFERENCE BOOKS:
1. Introduction to JAVA Programming Y. Daniel Liang, 6th Edition, Pearson
Education, 2007.
2. The J2EE Tutorial Stephanie Bodoff et al, 2nd Edition, Pearson Education, 2004.

CITSTUDENTS.IN

Page 2

Java/J2EE

06CS753

UNIT
No.

INTRODUCTION TO JAVA

Page No.
1-12

Java and Java applications; Java Development Kit (JDK);


Java is interpreted, Byte Code.

JVM , Object-oriented programming; Simple Java programs

Data types and other tokens: Boolean variables, int, long,


char, operators, arrays, white spaces, literals,

TS
.IN

Index Sheet

operators and Expressions: Arithmetic Operators, Bitwise


operators, Relational operators, The Assignment Operator,
The ? Operator; Operator Precedence; Logical expression;

Type casting; Strings , Control Statements: Selection


statements, iteration statements, Jump Statements

EN

CLASSES, INHERITANCE, EXCEPTIONS, APPLETS

13

Inheritance: Simple, multiple, and multilevel inheritance;


Overriding, overloading.

15

Exception handling: Exception handling in Java.

18

20

Requesting repainting; Using the Status Window; The HTML


APPLET tag; Passing parameters to Applets;
getDocumentbase() and getCodebase()

22

ApletContext and showDocument(); The AudioClip Interface;


The AppletStub Interface; Output to the Console.

23

TS

The Applet Class: Two types of Applets; Applet basics; Applet


Architecture; An Applet skeleton; Simple Applet display
method

CI
3

13-28

Classes: Classes in Java; Declaring a class; Class name;


Super classes; Constructors; Creating instances of class;
Inner classes

TU
D

Assigning values ,Creating and destroying objects; Access


specifiers.

MULTI THREADED PROGRAMMING, EVENT HANDLING

29-41

Multi Threaded Programming: What are threads? How to


make the classes threadable;

29

Extending threads; Implementing runnable; Synchronization;

30

CITSTUDENTS.IN

Page 3

Java/J2EE

06CS753
Changing state of the thread; Bounded buffer problems
33

Two event handling mechanisms

35

The delegation event model; Event classes; Sources of events

36

Event listener interfaces; Using the delegation event model

37

Adapter classes; Inner classes

39

SWINGS

42-49

Swings: The origins of Swing; Two key Swing features

42

Components and Containers

42

The Swing Packages; A simple Swing Application

45

Create a Swing Applet

46

Jlabel and ImageIcon

EN

47

JTextField;The Swing Buttons; JTabbedpane

48

JScrollPane; JList; JComboBox; JTable

49

JAVA 2 ENTERPRISE EDITION OVERVIEW, DATABASE


ACCESS:

TU
D

TS
.IN

Read-write problem, producer-consumer problems

Overview of J2EE and J2SE.

50
50

A Brief Overview of the JDBC process; Database Connection;

50

TS

The Concept of JDBC; JDBC Driver Types; JDBC Packages

Associating the JDBC/ODBC Bridge with the Database;

51

Statement Objects ,ResultSet;

52

Transaction Processing Metadata,. Data types; Exceptions.

53

CI
6

50-53

SERVLETS

54-60

Background

54

The Life Cycle of a Servlet; Using Tomcat for Servlet


Development; A simple Servlet

54

The Servlet API; The Javax.servlet Package

55

Reading Servlet Parameter; The Javax.servlet.http package

56

CITSTUDENTS.IN

Page 4

Java/J2EE
Handling HTTP Requests and Responses

57

Using Cookies

58

Session Tracking.

59

JSP, RMI

61-65

Java Server Pages (JSP): JSP, JSP Tags

61

Tomcat, Request String, User Sessions

62

Cookies, Session Objects

64

TS
.IN

06CS753

Java Remote Method Invocation: Remote Method Invocation


concept

64

Server side

65

Client side.

65

KSIMC

65

ENTERPRISE JAVA BEANS

TU
D

EN

Dic single windows agency SISI,NSIC,SIDBI,KSFC

Enterprise java Beans;

Deployment Descriptors

65

66-68

66
67
67

Entity Java Bean;

67

TS

Session Java Bean

68

CI

Message-Driven Bean, The JAR File.

CITSTUDENTS.IN

Page 5

Java/J2EE

06CS753
UNIT-1 INTRODUCTION TO JAVA

1. Introduction to Java
x Java is an object-oriented programming language developed by Sun
Microsystems, a company best known for its high-end Unix workstations.
x Java is modeled after C++

TS
.IN

x Java language was designed to be small, simple, and portable across platforms
and operating systems, both at the source and at the binary level (more about
this later).
x Java also provides for portable programming with applets. Applets appear in a
Web page much in the same way as images do, but unlike images, applets are
dynamic and interactive.

1.1 Java Is Platform-Independent

EN

x Applets can be used to create animations, figures, or areas that can respond to
input from the reader, games, or other interactive effects on the same Web
pages among the text and graphics.

TU
D

Platform-independence is a program's capability of moving easily from one


computer system to another.
x Platform independence is one of the most significant advantages that Java has over
other programming languages, particularly for systems that need to work on many
different platforms.
Java is platform-independent at both the source and the binary level.

TS

1.2 Java Development Kit (JDK)- Byte code

CI

x Bytecodes are a set of instructions that look a lot like machine code, but are not
specific to any one processor
x Platform-independence doesn't stop at the source level, however. Java binary files
are also platform-independent and can run on multiple platforms without the need to
recompile the source. Java binary files are actually in a form called bytecodes.

1.3 Object-Oriented Programming


x

Many of Java's object-oriented concepts are inherited from C++, the language on

which it is based, but it borrows many concepts from other object-oriented languages
as well.

CITSTUDENTS.IN

Page 6

Java/J2EE

06CS753

x Java includes a set of class libraries that provide basic data types, system input and
output capabilities, and other utility functions.

1.4 Creating a simple Java Program


Hello World example :
class HelloWorld {
public static void main (String args[]) {
System.out.println("Hello World! ");
}
}

EN

This program has two main parts:

TS
.IN

x These basic classes are part of the Java development kit, which also has classes
to support networking, common Internet protocols, and user interface toolkit
functions.
x Because these class libraries are written in Java, they are portable across
platforms as all Java applications are.

x All the program is enclosed in a class definitionhere, a class called


Hello World.

TU
D

x The body of the program (here, just the one line) is contained in a method
(function) called main(). In Java applications, as in a C or C++ program, main() is
the first method (function) that is run when the program is executed.
1.5 Compiling the above program :

In Sun's JDK, the Java compiler is called javac.

TS

ja v a c He lloW orld. j a va

CI

x When the program compiles without errors, a file called HelloWorld.class is


created, in the same directory as the source file. This is the Java bytecode file.
x Then run that bytecode file using the Java interpreter. In the JDK, the Java
interpreter is called simply java.
java HelloWorld
If the program was typed and compiled correctly, the output will
be : "Hello World!"

CITSTUDENTS.IN

Page 7

Java/J2EE

06CS753

2. V ariables and Data Types


x Variables are locations in memory in which values can be stored. They have a
name, a type, and a value.
x Java has three kinds of variables: instance variables, class variables, and
local variables.
x Instance variables, are used to define attributes or the state for a particular
object. Class variables are similar to instance variables, except their values apply
to all that class's instances (and to the class itself) rather than having different
values for each object.

TS
.IN

x Local variables are declared and used inside method definitions,


for example, for index counters in loops, as temporary variables, or to hold
values that you need only inside the method definition itself
Variable declarations consist of a type and a variable name:

in t myAge;

TU
D

St rin g
m yNam e;
boo le a n isT ired;

EN

Examples :

2. 1 I n t e g er t y p es .
Type Size Range

TS

byte 8 bits 128 to 127

short 16 bits 32,768 to 32,767


int 32 bits 2,147,483,648 to 2,147,483,647

CI

9223372036854775808 to 9223372036854775807 long 64 bits

2. 2 F l o a t i n g - p o i n t

This is used for numbers with a decimal part. Java floating-point numbers are
compliant with IEEE 754 (an international standard for defining floating-point
numbers and arithmetic).

CITSTUDENTS.IN

Page 8

Java/J2EE

06CS753

There are two floating-point types: float (32 bits, single-precision) and double (64
bits, double-precision).
2. 3 Ch a r
The char type is used for individual characters. Because Java uses the Unicode
character set, the char type has 16 bits of precision, unsigned.

TS
.IN

2. 4 B o o l e a n
The boolean type can have one of two values, true or false. Note that unlike in
other C-like languages, boolean is not a number, nor can it be treated as one. All
tests of Boolean variables should test for true or false.
2 . 5 Lite r a ls

programs. Number Literals

EN

Literals are used to indicate simple values in your Java

TU
D

x There are several integer literals. 4, for example, is a decimal integer literal of
type int
x A decimal integer literal larger than an int is automatically of type long.
x Floating-point literals usually have two parts: the integer part and the decimal
partfor example, 5.677777.
Boolean Literals

TS

Boolean literals consist of the keywords true and false. These keywords can
be used anywhere needed a test or as the only possible values for boolean
variables.

CI

2.6 Character Literals

Character literals are expressed by a single character surrounded by single


quotes: 'a', '#', '3', and so on. Characters are stored as 16-bit Unicode characters.
3. Expressions and Operators
x Expressions are the simplest form of statement in Java that actually
accomplishes something. Ex p r e s s i o n s are statements that return a value.
x O p e r a to r s are special symbols that are commonly used in expressions.

CITSTUDENTS.IN

Page 9

Java/J2EE

06CS753

Arithmetic and tests for equality and magnitude are common examples of
expressions. Because they return a valuethe value can be assigned to a
variable or test that value in other Java statements.
Operators in Java include arithmetic, various forms of assignment,
increment and decrement, and logical operations.
3. 1 A r i th m e t ic

TS
.IN

Java has five operators for basic arithmetic

O p e rator
Exam
Meaning
ple
+
Addition
3+4

Subtraction 5
*
Multiplication 5 * 5
/
Division
14 / 7
%

Modulus 20 % 7

TU
D

Example program :

EN

A r i t hm e t ic o pe r a t or s .

class ArithmeticTest {

public static void main (String args[]) {


short x = 6;
int y = 4;

TS

float a = 12.5f;

float b = 7f;
System.out.println("x + y = "
+

+
",

y
"

is

(
x

+ y));

CI

- y));
System.out.println("x - y = " (
+
x / y));
System.out.println("a is " + a + ", b is "

}}

System.out.println("a / b = " + (a / b));

+
y);

+
b;

Assignment operators.
Expression Meaning
x += y

x=x+y

CITSTUDENTS.I
N10

Page

Java/J2EE
x

06CS753

= y x = x y

x *= y

x=x*y

x = x / y x /= y

Incrementing and Decrementing

Exercise : write the difference between :


y = x++;
y

= ++x;

Comparison operators.
Example

==

x == 3

Not equal
Less than
Greater than
Less
than

x
x<
x>
x

TU
D

!=
<
>
<=

Equal

EN

Opera to r M eaning

TS
.IN

x++ increments the value of x by 1 just as if you had used the expression x = x + 1.
Similarly x-- decrements the value of x by 1.

or

>= Greater than or equal to x >= 3 Logical

TS

Operators

CI

x Expressions that result in boolean values (for example, the comparison


operators) can be combined by using logical operators that represent the logical
combinations
x AND, OR, XOR, and logical NOT.
x For AND combinations, use either the & or &&. The expression will be true
only if both expressions are also true
x For OR expressions, use either | or ||. OR expressions result in true if either or
both of the operands is also true
x In addition, there is the XOR operator ^, which returns true only if its
operands are different (one true and one false, or vice versa) and false otherwise
(even if both are true).
x In general, only the && and || are commonly used as actual logical
combinations. &, |, and ^ are more commonly used for bitwise logical

CITSTUDENTS.I
N11

Page

Java/J2EE

06CS753

operations.
x For NOT, use the ! operator with a single expression argument. The value of the
NOT expression is the negation of the expression; if x is true, !x is false.
Bitwise Operators
These are used to perform operations on individual bits in integers.

TS
.IN

O p e rator Meaning
Bitwise AND

Bitwise OR

Bitwise XOR

<<

Left shift

>>

Right shift

>>>

Zero fill right shift

Bitwise complement

<<=

Left shift assignment (x = x << y)

>>=

Right shift assignment (x = x >> y)

TU
D

EN

&

TS

>>>= Zero fill right shift assignment (x = x >>> y)


x&=y AND assignment (x = x & y)
x|=y OR assignment (x + x | y)
XOR assignment (x = x ^ y)

CI

x^=y

Operator Precedence

Operator precedence determines the order in which expressions are evaluated.


This, in some cases, can determine the overall value of the expression. For
example, take the following expression:
y=6+4/2

CITSTUDENTS.I
N12

Page

Java/J2EE

06CS753

Depending on whether the 6 + 4 expression or the 4 / 2 expression is evaluated


first, the value of y can end up being 5 or 8. In general, increment and decrement
are evaluated before arithmetic, arithmetic expressions are evaluated before
comparisons, and comparisons are evaluated before logical expressions.
Assignment expressions are evaluated last.
4 Arra ys

TS
.IN

Arrays in Java are actual objects that can be passed around and treated just like
other objects.
A r r a y s are a way to store a list of items. Each slot of the array holds an
individual element, and you can place elements into or change the contents or
those slots as you need to.
Three steps to create an array:
Declare a variable to hold the array.

2.

Create a new array object and assign it to the array variable.

3.

Store things in that array.

TU
D

E.g.

EN

1.

String[] names;
names = new String[10];
names [1] = n1;
names[2] = n2;

TS

...

4. 1 Multidim ensional A rr ays

CI

Java does not support multidimensional arrays. However, you can declare and
create an array of arrays (and those arrays can contain arrays, and so on, for
however many dimensions you need), and access them as you would C-style
multidimensional arrays:
int coords[] [] = new int[12] [12];
coords[0] [0] = 1; coords[0] [1] = 2;
5 C o n t r o l St a t em e nt

CITSTUDENTS.I
N13

Page

Java/J2EE

06CS753

5. 1 if C o n d i t i o na ls
x The if conditional, which enables you to execute different bits of code based
on a simple test in Java, is nearly identical to if statements in C.
x if conditionals contain the keyword if, followed by a boolean test,
followed by a statement (often a block statement) to execute if the test is true:
x if (x < y)
System.out.println("x is smaller than y");

if (x < y)

TS
.IN

An optional else keyword provides the statement to execute if the test is false:

System.out.println("x is smaller than y"); else


System.out.println("y is bigger");

EN

5. 2 T he C o n d i t i o nal Op e r a t o r

An alternative to using the if and else keywords in a conditional statement is to


use the conditional operator, sometimes called the ternary operator.

TU
D

The conditional operator is a ternary operator because it has three terms.


Syntax : test ? trueresult : falseresult

TS

The test is an expression that returns true or false, just like the test in the if
statement. If the test is true, the conditional operator returns the value of
trueresult; if it's false, it returns the value of falseresult. For example, the following
conditional tests the values of x and y, returns the smaller of the two, and assigns
that value to the variable smaller:

CI

int smaller = x < y ? x : y;


The conditional operator has a very low precedence; that is, it's usually evaluated
only after all its subexpressions are evaluated. The only operators lower in
precedence are the assignment operators..
5. 3 switch Conditionals
This is the switch or case statement; in Java it's switch and behaves as it does in C:

CITSTUDENTS.I
N14

Page

Java/J2EE

06CS753

switch
(test)
valueOne:

case

resultOne;
break;
case valueTwo:
resultTwo;

TS
.IN

break;
case valueThree:
resultThree;
break; ...
default: defaultresult;

EN

TU
D

In the switch statement, the test (a primitive type of byte, char, short, or int) is
compared with each of the case values in turn. If a match is found, the statement, or
statements after the test is executed. If no match is found, the default statement is
executed. The default is optional, so if there isn't a match in any of the cases and
default doesn't exist, the switch statement completes without doing anything.

5 . 4 f or L o o p s

CI

TS

The for loop, as in C, repeats a statement or block of statements some number of


times until a condition is matched. for loops are frequently used for simple
iteration in which you repeat a block of statements a certain number of times and
then stop, but you can use for loops for just about any kind of loop.
The for loop in Java looks roughly like this:
for (initialization; test; increment) { statements;
}
The start of the for loop has three parts:
x

Initialization is an expression that initializes the start of the loop. If you have

CITSTUDENTS.I
N15

Page

Java/J2EE

06CS753

a loop index, this expression might declare and initialize it, for example, int i = 0.
Variables that you declare in this part of the for loop are local to the loop itself;
they cease existing after the loop is finished executing. Test is the test that
occurs after each pass of the loop. The test must be a boolean expression or
function that returns a boolean value, for example, i < 10. If the test is true, the
loop executes. Once the test is false, the loop stops executing
Increment is any expression or function call. Commonly, the increment is used
to change the value of the loop index to bring the state of the loop closer to
returning false and completing.

EN

String strArray[] = new String[10];


int i; // loop index

TS
.IN

The statement part of the for loop is the statements that are executed each time
the loop iterates. Just as with if, you can include either a single statement here
or a block; the previous example used a block because that is more common.
Here's an example of a for loop that initializes all the values of a String array to
null strings:

TU
D

for (i = 0; i < strArray.length; i++)


strArray[i] = "";

5 . 5 wh ile a n d do L o op s

TS

Finally, there are while and do loops. while and do loops, like for loops, enable a
block of Java code to be executed repeatedly until a specific condition is met.
Whether you use a for loop, a while, or a do is mostly a matter of your pro
gramming style. while and do loop, are exactly the same as in C and C++ except
their test condition must be a boolean.

CI

5. 6 while Loops

The while loop is used to repeat a statement or block of statements as long as a


particular condition is true. while loops look like this:
while (condition)
bodyOfLoop; }

The co ndi tio n is a boolean expression. If it returns true, the while loop
executes the statements in bodyOfLoop and then tests the condition again,
repeating until the condition is false:

CITSTUDENTS.I
N16

Page

Java/J2EE

06CS753

int count = 0;
while ( count < array 1 .length && array 1 [count] !=0)
{ array2[count] = (float) array1[count++];
}
5 . 7 d o. . . w h i l e L o o ps

TS
.IN

The do loop is just like a while loop, except that do executes a given statement
or block until the condition is false. The main difference is that while loops test
the condition
before looping, making it possible that the body of the loop will never execute if
the condition is false the first time it's tested. do loops run the body of the loop at
least once before testing the condition. do loops look like this:

bodyOfLoop;
} while ( co n d i ti o n );

EN

do {

int x = 1;
do {

TU
D

Here, the bodyOfLoop part is the statements that are executed with each

System.out.println("Looping, round " + x); x++;

TS

} while (x <= 10);

Here's the output of these statements:

CI

Looping, round 1 Looping, round 2 Looping, round 3 Looping, round 4 Looping,


round 5 Looping, round 6
Looping, round Looping, round Looping, round Looping, round

CITSTUDENTS.I
N17

Page

Java/J2EE

06CS753

TS
.IN

UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS


1. Defining Classes, Class Name

To define a class, use the class keyword and the name of the class:

class MyClassName {
... }

EN

x If this class is a subclass of another class, use extends to indicate the superclass of
this
class:

...
}

TU
D

class myClassName extends mySuperClassName {

...
}

TS

x If this class implements a specific interface, use implements to refer to that


interface: class MyRunnableClassName implements Runnable {

CI

Super Classes

x Each class has a superclass (the class above it in the hierarchy), and each class can
have one or more subclasses (classes below that class in the hierarchy). Classes
further down in the hierarchy are said to inherit from classes further up in the
hierarchy.
x Subclasses inherit all the methods and variables from their superclassesthat is, in
any particular class, if the superclass defines behavior that your class needs, you
don't have to redefine it or copy that code from some other class. Your class

CITSTUDENTS.I
N18

Page

Java/J2EE

06CS753

automatically gets that behavior from its superclass, that superclass gets behavior
from its superclass, and so on all the way up the hierarchy.
x At the top of the Java class hierarchy is the class Object; all classes inherit from
this one superclass. Object is the most general class in the hierarchy; it defines
behavior inherited by all the classes in the Java class hierarchy. Each class farther
down in the hierarchy adds more information and becomes more tailored to a
specific purpose.

TS
.IN

E.g.
public class HelloAgainApplet extends java.applet.Applet { }
2. Constructors, Creating instances of a class

The following example demonstrates the creation of classes, creating objects and the
usage of constructors
class Motorcycle { }

EN

create some instance variables for this class

String make; String color; boolean engineState;

TU
D

Add some behavior (methods) to the class.


void startEngine() {

if (engineState == true)

System.out.println("The engine is already on."); else {

TS

engine State = true;

System.out.println("The engine is now on."); }

CI

The program looks like this now :

CITSTUDENTS.I
N19

Page

Java/J2EE

06CS753
class Motorcycle {

engine is already
on.");

String make;

engine
on.");

String color;

is

now

boolean engineState;

if (engineS tate == true)


System.out.println("The

TS
.IN

void startEngine() {

The showAtts method prints the current values of the instance variables in an instance
of your Motorcycle class. Here's what it looks like:
void showAtts() {

if (engineState == true)

EN

System. out .println ("This motorcycle is a " + color + " " + make);

System.out.println("The engine is on."); else System.out.println("The engine is off.");

TU
D

The showAtts method prints two lines to the screen: the make and color of the
motorcycle object, and whether or not the engine is on or off.
2.1 Add the main method

public static void main (String args[]) { Motorcycle m = new Motorcycle(); m.make =
"Yamaha RZ350";

TS

m.color = "yellow";

System.out.println("Calling showAtts..."); m.showAtts(); System.out.println("

CI

"); System.out.println("Starting
engine..."); m.startEngine();

System.out.println("");
System.out.println("Calling showAtts..."); m.showAtts(); System.out.println("

"); System.out.println("Starting
engine..."); m.startEngine();

CITSTUDENTS.I
N20

Page

Java/J2EE

06CS753

}
With the main() method, the Motorcycle class is now an application, and you can
compile it again and this time it'll run. Here's how the output should look:
Calling showAtts...
This motorcycle is a yellow Yamaha RZ350 The engine is off.
Starting engine... The engine is now on.

TS
.IN

Calling showAtts...

This motorcycle is a yellow Yamaha RZ350 The engine is on.


Starting engine...
The engine is already on.
3. Inheritance

EN

Inheritance is a powerful mechanism that means when you write a class you only have
to specify how that class is different from some other class; inheritance will give you
automatic access to the information contained in that other class.

TU
D

With inheritance, all classesthose you write, those from other class libraries that you
use, and those from the standard utility classes as wellare arranged in a strict
hierarchy
3.1 Single and Multiple Inheritance

TS

Single inheritance means that each Java class can have only one superclass (although
any given superclass can have multiple subclasses).

CI

In other object-oriented programming languages, such as C++, classes can have more
than one superclass, and they inherit combined variables and methods from all those
classes. This is called multiple inheritance.
Multiple inheritance can provide enormous power in terms of being able to create
classes that factor just about all imaginable behavior, but it can also significantly
complicate class definitions and the code to produce them. Java makes inheritance
simpler by being only singly inherited.
3.2 Overriding Methods

CITSTUDENTS.I
N21

Page

Java/J2EE

06CS753

x When a method is called on an object, Java looks for that method definition in the
class of that object, and if it doesn't find one, it passes the method call up the class
hierarchy until a method definition is found.
x Method inheritance enables you to define and use methods repeatedly in subclasses
without having to duplicate the code itself.

TS
.IN

x However, there may be times when you want an object to respond to the same
methods but have different behavior when that method is called. In this case, you
can override that method. Overriding a method involves defining a method in a
subclass that has the same signature as a method in a superclass. Then, when that
method is called, the method in the subclass is found and executed instead of the
one in the superclass.
3.3 Creating Methods that Override Existing Methods

TU
D

The PrintClass class.

EN

To override a method, all you have to do is create a method in your subclass that has
the same signature (name, return type, and parameter list) as a method defined by one
of your class's superclasses. Because Java executes the first method definition it finds
that matches the signature, this effectively "hides" the original method definition.
Here's a simple example

class PrintClass {

int x = 0; int y = 1;
void printMe() {

TS

System.out.println("X is " + x + ", Y is " + y);

System.out.println("I am an instance of the class " +


this.getClass().getName());

CI

Create a class called PrintSubClass that is a subclass of (extends) PrintClass.


class PrintSubClass extends PrintClass { int z = 3;

public static void main(String args[]) { PrintSubClass obj = new PrintSubClass(); obj
.printMe();
}
}

CITSTUDENTS.I
N22

Page

Java/J2EE

06CS753

Here's the output from PrintSubClass:


X is 0, Y is 1
I am an instance of the class PrintSubClass
In the main() method of PrintSubClass, you create a PrintSubClass object and call the
printMe() method. Note that PrintSubClass doesn't define this method, so Java looks
for it in each of PrintSubClass's superclassesand finds it, in this case, in PrintClass.
because printMe() is still defined in PrintClass, it doesn't print the z instance variable.

TS
.IN

To call the original method from inside a method definition, use the super keyword to
pass the method call up the hierarchy:
void myMethod (String a, String b) { // do stuff here
super.myMethod(a, b);
// maybe do more stuff here }

TU
D

4. Exception handling

EN

The super keyword, somewhat like the this keyword, is a placeholder for this class's
superclass. You can use it anywhere you can use this, but to refer to the superclass
rather than to the current class.

An exception is an event that occurs during the execution of a program that disrupts
the normal flow of instructions.
4.1 The Three Kinds of Exceptions

TS

x Checked exceptions are subject to the Catch or Specify Requirement. All exceptions
are checked exceptions, except for those indicated by Error, RuntimeException, and
their subclasses.

CI

x Errors are not subject to the Catch or Specify Requirement. Errors are those
exceptions indicated by Error and its subclasses.
x Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime
exceptions are those indicated by Runtime Except ion and its subclasses.

Valid Java programming language code must honor the Catch or Specify Requirement.
This means that code that might throw certain exceptions must be enclosed by either
of the following:
A try statement that catches the exception. The try must provide a handler for the
exception, as described in Catching and Handling Exceptions.

CITSTUDENTS.I
N23

Page

Java/J2EE

06CS753

A method that specifies that it can throw the exception. The method must provide a
throws clause that lists the exception, as described in Specifying the Exceptions
Thrown by a Method.
Code that fails to honor the Catch or Specify Requirement will not compile.
This example describes how to use the three exception handler components the try,
cat ch, and finally blocks
4.2 try block

TS
.IN

The first step in constructing an exception handler is to enclose the code that might
throw an exception within a try block. In general, a try block looks like the following.
try {
code

catch and finally blocks . . .


Example :
private Vector vector;

TU
D

private static final int SIZE = 10;

EN

PrintWriter out = null;


try {

TS

System.out.println("Entered try statement");

out = new PrintWriter(new FileWriter("OutFile.txt"));


for (int i = 0; i < SIZE; i++) {

CI

out.println("Value at: " + i + " = " + vector.elementAt(i));


}
}

The catch Blocks


You associate exception handlers with a try block by providing one or more catch
blocks directly after the try block. No code can be between the end of the try block and
the beginning of the first catch block.

CITSTUDENTS.I
N24

Page

Java/J2EE

06CS753

try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
Each catch block is an exception handler and handles the type of exception indicated
by its argument

TS
.IN

finally block

The runtime system always executes the statements within the finally block regardless
of what happens within the try block. So it's the perfect place to perform cleanup.
The following finally block for the write Li st method cleans up and then closes the
PrintWriter.

if (out != null) {

EN

finally {

System.out.println("Closing PrintWriter"); out . close();

TU
D

} else {

System.out.println("PrintWriter not open"); }


}

5. The Applet Class

TS

Applet Basics

x An applet is a special kind of Java program that a browser enabled with Java
technology can download from the internet and run.

CI

x An applet is typically embedded inside a web-page and runs in the context of the
browser.
x An applet must be a subclass of the java.applet.Applet class, which provides the
standard interface between the applet and the browser environment.
x Simple example :

public class HelloWorld extends java.applet.Applet {


public void paint(java.awt.Graphics g) {

CITSTUDENTS.I
N25

Page

Java/J2EE

06CS753

g.drawString("Hello World!",50,25); System.out.println("Hello World!");


}
}
An applet can be included in an HTML page, much in the same way an image is
included in a page.

TS
.IN

When Java technology enabled Browser is used to view a page that contains an applet,
the applet's code is transferred to your system and executed by the browser's Java
Virtual Machine (JVM)
Two Types of Applets

1 .Local applet - operate in single machine browser which is not connected in network,
2.Remote applet - remote applet operate over internet via network.
Applet Architecture

EN

Event driven :

An applet waits until an event occurs.

TU
D

The AWT notifies the applet about an event by calling event handler that has been
provided by the applet.
The applet takes appropriate action and then quickly return control to AWT All Swing
components descend from the AWT Container class

TS

User initiates interaction with an Applet (and not the other way around) An Applet
Skeleton
import java.awt.*;

import javax.swing.*;

CI

/*

<applet code="AppletSkel" width=300 height=100>


</applet>
*/
public class AppletSkel extends JApplet { // Called first.
public void init() {

CITSTUDENTS.I
N26

Page

Java/J2EE

06CS753

// initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start() {
// start or resume execution
}

TS
.IN

// Called when the applet is stopped. public void stop () {


// suspends execution
}

/* Called when applet is terminated. This is the last

public void destroy() {


// perform shutdown activities }

EN

method executed. */

TU
D

// Called when an applet's window must be restored. public void paint(Graphics g) {


// redisplay contents of window
}
}

TS

5.1 Simple Applet Display Methods

void drawstring(String message, int x, int y) - void setBackground(Color newColor)


void setForeground(Color newColor) Example :

CI

public class SimpleApplet extends Applet { public void paint (Graphics g) {


g.drawString("First Applet", 50, 50 ); }
}

Requesting Repainting
repaint( ) function is called when you have changed something and want your changes
to show up on the screen
repaint( ) is a request--it might not happen

CITSTUDENTS.I
N27

Page

Java/J2EE

06CS753

When you call repaint( ), Java schedules a call to update(Graphics g)


Here's what update does:
public void update(Graphics g) {
// Fills applet with background color, then
paint(g);

Syntax : public void showStatus(String status)


Parameters:

TS
.IN

Using The Status Window

status - a string to display in the status window.

Requests that the argument string be displayed in the "status window".

EN

Many browsers and applet viewers provide such a window, where the application can
inform users of its current state.
Example :

TU
D

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

public class NetExample extends Applet


{

private AppletContext browser = null;

TS

private Button showStatus = new Button("Show Status"); public void init()

Panel panel = new Panel();

CI

panel.setLayout(new GridLayout(1 ,2));


panel.add(showStatus);

setLayout(new BorderLayout()); add("South", panel);


browser = getAppletContext(); }
public boolean action(Event e, Object o)
{

CITSTUDENTS.I
N28

Page

Java/J2EE

06CS753

if (e.target == showStatus)
browser.showStatus("Here is something for your status line ..."); return true;
}
}
6. The HTML Applet Tag
The APPLET tag is used to start an applet from both an HTML document and
from an applet viewer.

An applet viewer will execute each APPLET tag that it finds in a separate
window,while web browsers like Netscape Navigator, Internet Explorer, and
HotJava will allow many applets on a single page.

TS
.IN

< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile

TU
D

[ALT = alte rnate Text]

EN

x The syntax for the standard APPLET tag is shown here. Bracketed items are
optional.

[NAME = appletInstanceName]

WIDTH = pixels HEIGHT = pixels


[ALIGN = alignment]

>

TS

[VSPACE = pixels] [HSPACE = pixels]

CI

[< PARAM NAME = AttributeName VALUE = Attribute Value>] [< PARAM NAME =
AttributeName2 VALUE = Attribute Value>] . . .
[HTML Displayed in the absence of Java]
</APPLET>

x CODEBASE is an optional attribute that specifies the base URL of the applet code,
which is the directory that will be searched for the applets executable class file
(specified by the CODE tag). The HTML documents URL directory is used as the
CODEBASE if this attribute is not specified. The CODEBASE does not have to be on
the host from which the HTML document was read.

CITSTUDENTS.I
N29

Page

Java/J2EE

06CS753

x CODE is a required attribute that gives the name of the file containing your
applets compiled .class file. This file is relative to the code base URL of the applet,
which is the directory that the HTML file was in or the directory indicated by
CODEBASE if set.
x ALT is an optional attribute used to specify a short text message that should be
displayed if the browser understands the APPLET tag but cant currently run Java
applets. This is distinct from the alternate HTML you provide for browsers that
dont support applets.

TS
.IN

x WIDTH AND HEIGHT are required attributes that give the size (in pixels) of the
applet display area.
x ALIGN is an optional attribute that specifies the alignment of the applet. This
attribute is treated the same as the HTML IMG tag with these possible values:
x LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE,
and ABSBOTTOM.

TU
D

EN

VSPACE AND HSPACE These attributes are optional. VSPACE specifies the
space, in pixels, above and below the applet. HSPACE specifies the space, in
pixels, on each side of the applet. Theyre treated the same as the IMG tags
VSPACE and HSPACE attributes.
PARAM NAME AND VALUE The PARAM tag allows you to specify
appletspecific arguments in an HTML page. Applets access their attributes
with the getParameter( ) method.

TS

Passing Parameters to Applets

Parameters are passed to applets in NAME=VALUE pairs in <PARAM> tags between


the opening and closing APPLET tags.

CI

Inside the applet, you read the values passed through the PARAM tags with
the getParameter() method of the java.applet.Applet class.
The applet parameter "Message" is the string to be drawn.

import java.applet. *; import


java.awt.*;

CITSTUDENTS.I
N30

Page

Java/J2EE

06CS753

public class DrawStringApplet extends Applet {


private String defaultMessage = "Hello!"; public
void paint(Graphics g) {
String inputFromPage = this .getParameter("Mes
sage");

}
}
HTML file that references the above applet.
<HTML> <HEAD>

</HEAD>
<BODY>

TU
D

This is the applet:<P>

EN

<TITLE> Draw String </TITLE>

TS
.IN

if (inputFromPage == null) inputFromPage = defaultMessage;


g.drawString(inputFromPage, 50, 25);

<APPLET code="DrawStringApplet" width="3 00" height="50">


<PARAM name="Message" value="Howdy, there!"> This page will be very boring if
your

TS

browser doesn't understand Java.


</APPLET>

</BODY> </HTML>

CI

getDocumentBase() and getCodeBase()

Syntax : public URL getDocumentBase()


Returns:

the URL of the document that contains this applet.


x Gets the URL of the document in which this applet is embedded.
x For example, suppose an applet is contained within the document:

CITSTUDENTS.I
N31

Page

Java/J2EE

06CS753

http://java.sun.com/products/jdk/1.2/index.html
x The document base is:
http://java.sun.com/products/jdk/1.2/index.html
Syntax : public URL getCodeBase()
Returns:
the base URL of the directory which contains this applet.

TS
.IN

x Gets the base URL. This is the URL of the directory which contains this applet.
x Example segments:
URL codeBase = getCodeBase();

Image myImage = getImage(codeBase, "images/myimage.gif"); Applet Context and


showDocument()

The AudioClip Interface

EN

AppletContext is an interface that provides the means to control the browser


environment in which the applet is running.

x The AudioC lip interface is a simple abstraction for playing a sound clip.

TU
D

x Multiple Audi oC lip items can be playing at the same time, and the resulting
sound is mixed together to produce a composite.
x It has the following methods :
play

TS

public abstract void play()

loop

Starts playing this audio clip. Each time this method is


called, the clip is restarted from the beginning.

CI

stop

public abstract void loop()


public abstract void stop()
Stops playing this audio clip.

The AppletStub Interface


The AppletStub interface provides a way to get information from the run-time browser
environment.

CITSTUDENTS.I
N32

Page

Java/J2EE

06CS753

The Applet class provides methods with similar names that call these methods.
Methods
public abstract boolean isActive ()
The isActive() method returns the current state of the applet. While an applet is
initializing, it is not active, and calls to isActive() return false. The system marks the
applet active just prior to calling start(); after this point, calls to isActive() return true.
x public abstract URL getDocumentBase ()

x public abstract URL getCodeBase ()

TS
.IN

The getDocumentBase() method returns the complete URL of the HTML file that
loaded the applet. This method can be used with the getImage() or getAudioClip()
methods to load an image or audio file relative to the HTML file.

The getCodeBase() method returns the complete URL of the .class file that contains the
applet. This method can be used with the getImage() method or the getAudioClip()
method to load an image or audio file relative to the .class file.

EN

x public abstract String getParameter (String name)

TU
D

The getParameter() method allows you to get parameters from <PARAM> tags within
the <APPLET> tag of the HTML file that loaded the applet. The name parameter of
getParameter() must match the name string of the <PARAM> tag; name is case
insensitive. The return value of getParameter() is the value associated with name; it is
always a String regardless of the type of data in the tag. If name is not found within
the <PARAM> tags of the <APPLET>, getParameter() returns null.
x public abstract AppletContext getAppletContext ()

TS

The getAppletContext() method returns the current AppletContext of the applet. This
is part of the stub that is set by the system when setStub() is called.
x public abstract void appletResize (int width, int height)

CI

The appletResize() method is called by the resize method of the Applet class. The
method changes the size of the applet space to width x height. The browser must
support changing the applet space; if it doesn't, the size remains unchanged
Output To the Console

The drawString method can be used to output strings to the console. The position of
the text can also be specified.
The following prog shows this concept:
public class ConsolePrintApplet1 extends java.applet.Applet
{

CITSTUDENTS.I
N33

Page

Java/J2EE

06CS753

public void init () {


// Put code between this line
double x = 5.0; double y = 3.0;
System.out.println( "x * y = "+ (x*y) );
System.out.println( "x / y = "+ (x/y) );
//

// and this line.

TU
D

EN

// Paint message in the applet window. Public

TS
.IN

1.

TS

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING


What are Threads?

A thread is a single path of execution of code in a program.

CI

x A Multithreaded program contains two or more parts that can run


concurrently.
x Each part of such a program is called a Thread.
x Each thread defines a separate path of execution. Multithreading is a
specialized form of Multitasking.

1.1 How to make the classes threadable


A class can be made threadable in one of the following ways

CITSTUDENTS.I
N34

Page

Java/J2EE

06CS753

(1) implement the Runnable Interface and apply its run() method.
(2) extend the Thread class itself.
1. Implementing Runnable Interface: The easiest way to create a thread is to create
a class that implements the Runnable interface. To implement Runnable, a class
need only implement a single method called run().
The Format of that function is public void run().

TS
.IN

2. Extending Thread: The second way to create a thread is to create a new class that
extends the Thread class and then to create an instance of this class. This class
must override the run() method which is the entry point for the new thread.
1.2 Extending Threads

TU
D

EN

You can inherit the Thread class as another way to create a thread in your
program. When you declare an instance of your class, youll also have access to
members of the Thread class. Whenever your class inherits the Thread class, you
must override the run() method, which is an entry into the new thread. The
following example shows how to inherit the Thread class and how to override the
run() method. This example defines the MyThread class, which inherits the Thread
class. The constructor of the MyThread class calls the constructor of the Thread
class by using the super keyword and passes it the name of the new thread, which
is My thread. It then calls the start() method to activate the new thread. The start()
method calls the run() method of the MyThread class
class MyThread extends Thread {
MyThread() {

TS

super("My thread");
start();

CI

public void run() {


System.out.println("Child thread started");
System.out.println("Child thread terminated");
}}
class Demo {

CITSTUDENTS.I
N35

Page

Java/J2EE

06CS753

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


MyThread(); System.out.println("Main
thread started");
System.out.println("Main thread terminated");
}}
1.3

Implementing Runnable

TS
.IN

The example in the next segment demonstrates the use of Runnable and its
implementation.
Synchronization

1. Two or more threads accessing the same data simultaneously may lead to loss of
data integrity. In order to avoid this java uses the concept of monitor. A monitor is an
object used as a mutually exclusive lock.

EN

2. At a time only one thread can access the Monitor. A second thread cannot enter the
monitor until the first comes out. Till such time the other thread is said to be waiting.

TU
D

3. The keyword Synchronized is use in the code to enable synchronization and it can
be used along with a method.
Changing the state of thread

CI

TS

There might be times when you need to temporarily stop a thread from processing
and then resume processing, such as when you want to let another thread use the
current resource. You can achieve this objective by defining your own suspend and
resume methods, as shown in the following example. This example defines a
MyThread class. The MyThread class defines three methods: the run() method, the
suspendThread() method, and the resumeThread() method. In addition, the
MyThread class declares the instance variable suspended, whose value is used to
indicate whether or not the thread is suspended.
class MyThread implements Runnable {
String name;
Thread t;
boolean suspended;
MyThread() {

CITSTUDENTS.I
N36

Page

Java/J2EE

06CS753

t = new Thread(this, "Thread");


suspended = false ; t.start();
}
public void run() {
try {
for (int i = 0; i < 10; i++) { System.out.println("Thread: " + i ); Thread.sleep(200);
synchronized (this) {

TS
.IN

while (suspended) {
wait();
}
}
}

EN

} catch (InterruptedException e ) { System.out.println("Thread: interrupted."); }


System.out.println("Thread exiting.");
}

TU
D

void suspendThread() { suspended = true;


}

synchronized void resumeThread() {

TS

suspended = false;
notify();
}

CI

class Demo {

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


try{
Thread.sleep(1000);
Thread.sleep(1000);

CITSTUDENTS.I
N37

t1.suspendThread();

System.out.println("Thread:

Suspended");

Page

Java/J2EE

06CS753

t1.resumeThread(); System.out.println("Thread: Resume");


} catch ( InterruptedException e) {
}
try {
t1.t.join();

"Main Thread: interrupted"); }


}
}
2.

Bounded Buffer Problem

EN

Problem Description :

TS
.IN

} catch ( InterruptedException e) { System.out.println (

In computer science the producer-consumer problem (also known as the boundedbuffer

TU
D

problem) is a classical example of a multi-process synchronization problem. The


problem describes two processes, the producer and the consumer, who share a
common, fixed-size buffer.

TS

The producer's job is to generate a piece of data, put it into the buffer and start again.
At the same time the consumer is consuming the data (i.e. removing it from the
buffer) one piece at a time. The problem is to make sure that the producer won't try to
add data into the buffer if it's full and that the consumer won't try to remove data
from an empty buffer. This is the code for solving the above stated:

CI

class BufferItem {

public volatile double value = 0;


// multiple threads access public volatile
boolean occupied = false; // so make these `volatile' }
class BoundedBuffer { // designed for a single producer thread and // a single
consumer thread
private int numSlots = 0;
private BufferItem[] buffer = null;

CITSTUDENTS.I
N38

Page

Java/J2EE

06CS753

private int putIn = 0, takeOut = 0;


// private int count = 0;
public BoundedBuffer(int numSlots) {
if (numSlots <= 0) throw
this.numSlots = numSlots;

new

IllegalArgumentException("numSlots<=0");

buffer = new BufferItem[numSlots];

putIn = (putIn + 1) % numSlots;


// count++;

// race condition!!! }

public double fetch() {


double value;

TS
.IN

for (int i = 0; i < numSlots; i++) buffer[i] = new BufferItem();

EN

while (!buffer[takeOut].occupied) // busy wait Thread.currentThread().yield();


value = buffer[takeOut].value; // C

//

// D takeOut = (takeOut + 1) % numSlots;

TU
D

buffer [takeOut] .occupied = false;

count--; // race condition!!! return value;

}
}

TS

Read-Write problem

CI

x Read/Write locks provides a synchronization mechanism that allow threads in an


application to more accurately reflect the type of access to a shared resource that they
require.
x Many threads can acquire the same read/write lock if they acquire a shared read lock
on the read/write lock object.

x Only one thread can acquire an exclusive write lock on a read/write lock object.
x When an exclusive write lock is held, no other threads are allowed to hold any lock.
public class Read WriteLock{
private int readers

CITSTUDENTS.I
N39

= 0;
Page

Java/J2EE

06CS753

private int writers

= 0; private int writeRequests = 0;

public synchronized void lockRead() throws InterruptedException{ while(writers > 0


|| writeRequests > 0){
wait();
}
readers++;

TS
.IN

public synchronized void unlockRead(){ readers--;


notifyAll();
}

writeRequests++;

EN

public synchronized void lockWrite() throws InterruptedException{

while(readers > 0 || writers > 0){ wait();

TU
D

}
writeRequests--;
writers++;
}

TS

public synchronized void unlockWrite() throws InterruptedException{ writers--;


notifyAll();
}

CI

Producer-Consumer problems
x In producer/consumer synchronizations, producer processes make items available
to consumer processes.
x

Examples are a message sender and a message receiver, or two machines working
on items in sequence.

CITSTUDENTS.I
N40

Page

Java/J2EE
x

06CS753

The synchronization here must ensure that the consumer process does not
consume more items than have been produced. If necessary, the consumer process
is blocked (must wait) if no item is available to be consumed.

x Producer and consumer processes are coupled by a buffer to allow asynchronous


production and consumption.

3.

Event Handling

TS
.IN

x The buffer can be bounded (have a capacity limit) or unbounded (be able to store
an unlimited number of items).

In Java, events represent all activity that goes on between the user and the application.
Two event handling mechanisms :

EN

Delegation event model : It defines standard and consistent mechanisms to generate


and process events. Here the source generates an event and sends it to on or more
listeners. The listener simply waits until it receives an event. Once it is obtained, It
processes this event and returns. Listeners should register themselves with a source in
order to receive an even notification. Notifications are sent only to listeners that want
to receive them.

TU
D

Events

TS

In the delegation model, an event is an object that describes a state change in a source.
It can be generated as a consequence of a person interacting with the elements in a
graphical user interface. Some of the activities that cause events to be generated are :
pressing a button, entering a character via the keyboard, selecting an item in a list,
and clicking the mouse. Events may also occur that are not directly caused by
interactions with a user interface. For example, an event may be generated when a
timer expires, a counter exceeds a value, a software or hardware failure occurs, or an
operation is completed.

CI

Event Classes

The classes that represent events are at the core of Javas event handling mechanism.
EventObject : It is at the root of the Java event class hierarchy in java.util. It is the
superclass for all events. Its one constructor is shown here: EventObject(Object src)
Here, src is the object that generates this event. EventObject contains two methods:
getSource( ) and toString( ). The getSource( ) method returns the source of the event.
EventObject is a superclass of all events.
The ActionEvent Class :

CITSTUDENTS.I
N41

Page

Java/J2EE

06CS753

An ActionEvent is generated when a button is pressed, a list item is double-clicked, or


a menu item is selected. The ActionEvent class defines four integer constants that can
be used to identify any modifiers associated with an action event: ALT_MASK,
CTRL_MASK, META_MASK, and SHIFT_MASK.
ActionEvent has these three constructors: ActionEvent(Object src,
int type, String cmd) ActionEvent(Object src, int type,
String cmd, int modifiers)

TS
.IN

ActionEvent(Object src, int type, String cmd, long when, int modifiers) Here, src is a
reference to the object that generated this event. The type of the event is specified by
type, and its command string is cmd. The argument modifiers indicates which modifier
keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was
generated. The when parameter specifies when the event occurred

EN

x The AdjustmentEvent Class An AdjustmentEvent is generated by a scroll


bar
x The ComponentEvent Class A ComponentEvent is generated when the size,
position, or visibility of a component is changed. There are four types of
component events

TU
D

x The ContainerEvent Class A ContainerEvent is generated when a


component is added to or removed from a container
x The FocusEvent Class : A FocusEvent is generated when a component gains
or loses input focus

TS

x The InputEvent Class : The abstract class InputEvent is a subclass of


ComponentEvent and is the superclass for component input events. Its
subclasses are KeyEvent and MouseEvent.

CI

x The ItemEvent Class : An ItemEvent is generated when a check box or a list


item is clicked or when a checkable menu item is selected or deselected

x The KeyEvent Class A KeyEvent is generated when keyboard input occurs.

x The MouseEvent Class There are eight types of mouse events


x The MouseWheelEvent Class The MouseWheelEvent class encapsulates a
mouse wheel event.

CITSTUDENTS.I
N42

Page

Java/J2EE

06CS753
x The TextEvent Class Instances of this class describe text events. These are
generated

by text fields and text areas when characters are entered by a user or program.
x The WindowEvent Class There are ten types of window events. The
WindowEvent
class defines integer constants that can be used to identify them.

TS
.IN

Sources of Events
Event Source Description :

x Button - Generates action events when the button is pressed.

x Checkbox - Generates item events when the check box is selected or


deselected.

EN

x Choice - Generates item events when the choice is changed.

x List - Generates action events when an item is double-clicked; generates item


events

TU
D

x when an item is selected or deselected.

x Menu Item - Generates action events when a menu item is selected;


generates item
events when a checkable menu item is selected or deselected.

TS

x Scrollbar - Generates adjustment events when the scroll bar is manipulated.


x Text components - Generates text events when the user enters a character.

CI

x Window - Generates window events when a window is activated, closed,


deactivated,
deiconified, iconified, opened, or quit.

Event Listener Interfaces


Listeners are created by implementing one or more of the interfaces defined by the
java.awt.event package.

When an event occurs, the event source invokes the appropriate method defined by
the listener and provides an event object as its argument.

CITSTUDENTS.I
N43

Page

Java/J2EE

06CS753

Interface Description
ActionListener - Defines one method to receive action events.
AdjustmentListener - Defines one method to receive adjustment events.
ComponentListener - Defines four methods to recognize when a component is
hidden, moved, resized, or shown.
ContainerListener - Defines two methods to recognize when a component is added to
or removed from a container.

TS
.IN

FocusListener - Defines two methods to recognize when a component gains or loses


keyboard focus.
ItemListener - Defines one method to recognize when the state of an item changes.
KeyListener - Defines three methods to recognize when a key is pressed, released, or
typed.

EN

MouseListener - Defines five methods to recognize when the mouse is clicked, enters
a component, exits a component, is pressed, or is released.
MouseMotionListener - Defines two methods to recognize when the mouse is
dragged or moved.

TU
D

MouseWheelListener - Defines one method to recognize when the mouse wheel is


moved.

TS

TextListener - Defines one method to recognize when a text value changes.


WindowFocusListener - Defines two methods to recognize when a window gains or
loses input focus.
WindowListener Defines seven methods to recognize when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.

CI

Using the Delegation Event Model


Applet programming using the delegation event model is done following these two
steps:
1. Implement the appropriate interface in the listener so that it will receive the type of
event desired.
2. Implement code to register and unregister (if necessary) the listener as a recipient
for the event notifications.
Adapter Classes

CITSTUDENTS.I
N44

Page

Java/J2EE

06CS753

Definition : An adapter class provides an empty implementation of all methods in an


event listener interface.
Adapter classes are useful when you want to receive and process only some of the
events that are handled by a particular event listener interface.

x New class to act as an event listener by extending one of the adapter classes and
implementing only those events in which you are interested.

TS
.IN

x For example, the MouseMotionAdapter class has two methods, mouseDragged( )


and mouseMoved( ). The signatures of these empty methods are exactly as
defined in the MouseMotionListener interface. If you were interested in only
mouse drag events, then you could simply extend MouseMotionAdapter and
implement mouseDragged( ). The empty implementation of mouseMoved( )
would handle the mouse motion events for you.
The following example demonstrates an adapter.

EN

// Demonstrate an adapter. import java.awt.*;


import java.awt.event.*; import java.applet. *;
/*

</applet>
*/

TU
D

<applet code="AdapterDemo" width=300 height=1 00>

public class AdapterDemo extends Applet {

TS

public void init() {

addMouseListener(new MyMouseAdapter(this));

CI

addMouseMotionListener(new MyMouseMotionAdapter(this));
}}

class MyMouseAdapter extends MouseAdapter {


AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;

CITSTUDENTS.I
N45

Page

Java/J2EE

06CS753

}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}}

AdapterDemo adapterDemo;

TS
.IN

class MyMouseMotionAdapter extends MouseMotionAdapter {

public MyMouseMotionAdapter(AdapterDemo adapterDemo) {


this.adapterDemo = adapterDemo;
}

EN

// Handle mouse dragged.


public void mouseDragged(MouseEvent me) {

}}
Inner Classes

TU
D

adapterDemo.showStatus("Mouse dragged");

Consider the applet shown in the following listing. It does not use an inner class. Its
goal is to display the string

CI

TS

Mouse Pressed in the status bar of the applet viewer or browser when the mouse is
pressed. There are two top-level classes in this program. MousePressedDemo extends
Applet, and MyMouseAdapter extends MouseAdapter. The init( ) method of
MousePressedDemo instantiates MyMouseAdapter and provides this object as an
argument to the addMouseListener( ) method.
Notice that a reference to the applet is supplied as an argument to the
MyMouseAdapter constructor. This reference is stored in an instance variable for
later use by the mousePressed( )
method.
// This applet does NOT use an inner class.
import java.applet. *;

CITSTUDENTS.I
N46

Page

Java/J2EE

06CS753

import java.awt.event.*;
/*
<applet code="MousePressedDemo" width=200 height=100> </applet>
*/
public class MousePressedDemo extends Applet {
public void init() {

}}
class
MyMouseAdapter
mousePressedDemo;

extends

TS
.IN

addMouseListener(new MyMouseAdapter(this));

MouseAdapter

EN

public
MyMouseAdapter(MousePressedDemo
this.mousePressedDemo = mousePressedDemo;
}

MousePressedDemo

mousePressedDemo)

me)

CI

TS

TU
D

public
void
mousePressed(MouseEvent
mousePressedDemo.showStatus("Mouse Pressed.");

CITSTUDENTS.I
N47

Page

Java/J2EE

06CS753
UNIT-4: SWINGS

Swing is built on top of AWT and is entirely written in Java, using AWTs lightweight
component support. In particular, unlike AWT, t he architecture of Swing components
makes it easy to customize both their appearance and behavior. Components from AWT
and Swing can be mixed, allowing you to add Swing support to existing AWT-based
programs. For example, swing components such as JSlider, JButton and JCheckbox could
be used in the same program with standard AWT labels, textfields and scrollbars.

TS
.IN

1. Three parts
Component set (subclasses of JComponent) Support classes, Interfaces
Swing Components and Containers

JLabel Component

EN

Swing components are basic building blocks of an application. Swing toolkit has a
wide range of various widgets. Buttons, check boxes,sliders, list boxes etc. Everything
a programmer needs for his job. In this section of the tutorial, we will describe several
useful components.

JCheckBox

TU
D

JLabel is a simple component for displaying text, images or both. It does not react to
input events.

JCheckBox is a widget that has two states. On and Off. It is a box with a label JSlider

TS

JSlider is a component that lets the user graphically select a value by sliding a knob
within a bounded interval
JComboBox

CI

Combobox is a component that combines a button or editable field and a drop-down


list. The user can select a value from the drop-down list, which appears at the user's
request.
JProgressBar

A progress bar is a widget that is used, when we process lengthy tasks. It is animated
so that the user knows, that our task is progressing
JToggleButton

CITSTUDENTS.I
N48

Page

Java/J2EE

06CS753

JToggleButton is a button that has two states. Pressed and not pressed. You toggle
between these two states by clicking on it
Containers
Swing contains a number of components that provides for grouping other
components together.
In AWT, such components extended java.awt.Container and included Panel, Window,
Frame, and Dialog.

TS
.IN

1.1 A Simple Container

JPanel is Swings version of the AWT class Panel and uses the same default layout,
FlowLayout. JPanel is descended directly from JComponent.

EN

JFrame is Swings version of Frame and is descended directly from that class. The
components added to the frame are referred to as its contents; these are managed by
the contentPane. To add a component to a JFrame, we must use its contentPane
instead.
JInternalFrame is confined to a visible area of a container it is placed in. It can be
iconified , maximized and layered.

TU
D

JWindow is Swings version of Window and is descended directly from that class.
Like Window, it uses BorderLayout by default.
JDialog is Swings version of Dialog and is descended directly from that class. Like
Dialog, it uses BorderLayout by default. Like JFrame and JWindow,

TS

JDialog contains a rootPane hierarchy including a contentPane, and it allows layered


and glass panes. All dialogs are modal, which means the current
thread is blocked until user interaction with it has been completed. JDialog class is
intended as the basis for creating custom dialogs; however, some

CI

of the most common dialogs are provided through static methods in the class
JOptionPane.
Jlabel and ImageIcon
Syntax :

public class JLabel

extends JComponent
implements SwingConstants, Accessible

CITSTUDENTS.I
N49

Page

Java/J2EE
x

06CS753

It is a display area for a short text string or an image, or both.

x A label does not react to input events. As a result, it cannot get the keyboard focus.
x A label can display a keyboard alternative as a convenience for a nearby
component that has a keyboard alternative but can't display it.
x A JLabel object can display either text, an image, or both.
By default, labels are vertically centered in their display area.

Text-only labels are leading edge aligned, by default; image-only labels are
horizontally centered, by default.

TS
.IN

Can use the setIconTextGap method to specify how many pixels should appear
between the text and the image. The default is 4 pixels.
ImageIcon

EN

Syntax :
public ImageIcon(String filename)
{

TU
D

this(filename, filename);
}

Creates an ImageIcon from the specified file. The image will be preloaded by using
MediaTracker to monitor the loading state of the image.

TS

The specified String can be a file name or a file path. When specifying a path, use the
Internet-standard forward-slash ("/") as a separator. (The string is converted to an
URL, so the forward-slash works on all systems.)

CI

For example, specify:

new ImageIcon("images/myImage.gif")
The description is initialized to the filename string.
Example of JLabel with ImageIcon :

import java.awt.FlowLayout; import java.awt.HeadlessException;


import javax.swing.Icon;

CITSTUDENTS.I
N50

Page

Java/J2EE

06CS753

import javax.swing.ImageIcon; import javax.swing.JFrame; import


javax.swing.JLabel;
public class Main extends JFrame {
public Main() throws HeadlessException { setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new
FlowLayout(FlowLayout.LEFT));

TS
.IN

Icon icon = new ImageIcon("a.png");


JLabel label1 = new JLabel("Full Name :", icon, JLabel.LEFT);

JLabel label2 = new JLabel("Address :", JLabel.LEFT); label2.setIcon(new


ImageIcon("b.png"));
getContentPane().add(label1); getContentPane().add(label2);
}

EN

public static void main(String[] args) { new Main().setVisible(true);


}

JTextField

TU
D

x JTextField is a lightweight component that allows the editing of a single line of


text.
JTextField is intended to be source-compatible with java.awt.TextField where it is

TS

reasonable to do so. This component has capabilities not found in the


java.awt.TextField class.

CI

x JTextField has a method to establish the string used as the command string for the
action event that gets fired.

The java.awt.TextField used the text of the field as the command string for the
ActionEvent.

x JTextField will use the command string set with the setActionCommand method if
not null, otherwise it will use the text of the field as a compatibility with
java.awt.TextField.

CITSTUDENTS.I
N51

Page

Java/J2EE

06CS753

2. Swing Package

Syntax :
public class JButton extends AbstractButton implements Accessible

package com.ack.gui.swing.simple;
import java.awt.*;

TS
.IN

An implementation of a "push" button. Buttons can be configured, and to some degree


controlled, by Actions. Using an Action with a button has many benefits beyond
directly configuring a button.

import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import


javax.swing.*;

EN

public class SimpleSwingButtons extends JFrame {


public static void main( String[] argv ) {

TU
D

SimpleSwingButtons myExample = new SimpleSwingButtons( "Simple Swing


Buttons" );

public SimpleSwingButtons( String title ) {


super( title );

TS

setSize( 150, 150 );

add WindowListener( new WindowAdapter() { public void windowClosing(


WindowEvent we ) { dispose();

CI

System.exit( 0 );
}

} );

init();
setVisible( true );
}

CITSTUDENTS.I
N52

Page

Java/J2EE

06CS753

private void init() {


JPanel my_panel = new JPanel();
my_panel.setLayout( new GridLayout( 3, 3 ) ); for( int i = 1; i < 10; i++ ) {
ImageIcon icon = new ImageIcon( i + ".gif" ); JButton jb = new JButton( icon );
jb.setToolTipText( i + ".gif" );

}
getContentPane().add( my_panel );

TS
.IN

my_panel.add( jb );

my_panel.setBorder( BorderFactory.createEtchedBorder() );
}

JTabbedpane

EN

Syntax : public class JTabbedPane

TU
D

extends JComponent

implements Serializable, Accessible, SwingConstants


x

A component that lets the user switch between a group of components by clicking
on a tab with a given title and/or icon.

A tab is represented by an index corresponding to the position it was added in,


where the first tab has an index equal to 0 and the last tab has an index equal to the
tab count minus

CI

TS

x Tabs/components are added to a TabbedPane object by using the addTab and


insertTab methods.

The TabbedPane uses a Single SelectionModel to represent the set of tab indices
and the currently selected index. If the tab count is greater than 0, then there will
always be a selected index, which by default will be initialized to the first tab. If
the tab count is 0, then the selected index will be -1.

JScrollPane
Syntax : public class JScrollPane

CITSTUDENTS.I
N53

Page

Java/J2EE

06CS753

extends JComponent
implements ScrollPaneConstants, Accessible
x

Provides a scrollable view of a lightweight component.

x A JScrollPane manages a viewport, optional vertical and horizontal scroll bars, and
optional row and column heading viewports.

TS
.IN

x The JViewport provides a window, or "viewport" onto a data source -- for


example, a text file. That data source is the "scrollable client" (aka data model)
displayed by the JViewport view.
A JScrollPane basically consists of JScrollBars, a JViewport, and the wiring
between them, as shown in the diagram at right.

JList

extends JComponent

EN

Syntax : public class JList

implements Scrollable, Accessible

TU
D

A component that allows the user to select one or more objects from a list. A separate
model, ListModel, represents the contents of the list.
// Create a JList that displays the strings in data[]
String[] data = {"one", "two", "three", "four"}; JList dataList = new JList(data);
JComboBox

TS

Syntax : public class JComboBox


extends JComponent

CI

implements ItemSelectable, ListDataListener, ActionListener, Accessible


x

A component that combines a button or editable field and a drop-down list.

x The user can select a value from the drop-down list, which appears at the user's
request.

If you make the combo box editable, then the combo box includes an editable field
into which the user can type a value.

JTable

CITSTUDENTS.I
N54

Page

Java/J2EE

06CS753

Syntax : public class JTable


extends JComponent
implements TableModelListener, Scrollable, TableColumnModelListener,
ListSelectionListener, CellEditorListener, Accessible

The JTable is used to display and edit regular two-dimensional tables of cells.

The JTable has many facilities that make it possible to customize its rendering and

TS
.IN

editing but provides defaults for these features so that simple tables can be set up
easily.

For example, to set up a table with 10 rows and 10 columns of numbers:

TableModel dataModel = new AbstractTableModel() {

EN

public int getColumnCount() { return 10; }


public int getRowCount() { return 10;}

TU
D

public Object getValueAt(int row, int col) { return new Integer(row*col); }


}

JTable table = new JTable(dataModel); JScrollPane scrollpane = new JScrollPane(table);


1) Swing demo

TS

import javax.swing.*;
class swingdemo {
swingdemo() {

CI

// Create a new JFrame container.


JFrame jfrm = new JFrame("A Simple Swing Application");
// Give the frame an initial size.
jfrm.setSize(275, 100);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

CITSTUDENTS.I
N55

Page

Java/J2EE

06CS753

// Create a text-based label.


JLabel jlab = new JLabel(" Swing means powerful GUIs.");
// Add the label to the content pane.
jfrm.getContentPane().add(jlab);
// Display the frame.

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

TS
.IN

jfrm.setVisible(true);

// Create the frame on the event dispatching thread.


SwingUtilities.invokeLater(new Runnable() {

new swingdemo();
}

TU
D

});

EN

public void run() {

}
}

TS

2) // Demonstrate JToggleButton.
import java.awt.*;

CI

import java.awt.event.*;
import javax.swing.*;

/*

<applet code="jtoggle" width=200 height=80>


</applet>
*/

CITSTUDENTS.I
N56

Page

Java/J2EE

06CS753

public class jtoggle extends JApplet {


JLabel jlab;
JToggleButton jtbn;
public void init() {
try {
SwingUtilities.invokeAndWait(

TS
.IN

new Runnable() {
public void run() {
makeGUI();
}

);
} catch (Exception exc) {

EN

TU
D

System.out.println("Can't create because of " + exc);


}
}

TS

private void makeGUI() {

// Change to flow layout.

CI

getContentPane().setLayout(new FlowLayout());
// Create a label.
jlab = new JLabel("Button is off.");
// Make a toggle button.
jtbn = new JToggleButton("On/Off");
// Add an item listener for the toggle button.

CITSTUDENTS.I
N57

Page

Java/J2EE

06CS753

jtbn.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
if(jtbn.isSelected())
jlab.setText("Button is on.");
else
jlab.setText("Button is off.");

TS
.IN

});

// Add the toggle button and label to the content pane.

getContentPane().add(jlab);
}

TU
D

EN

getContentPane().add(jtbn);

3) // Demonstrate JTextField.
import java.awt.*;

TS

import java.awt.event.*;
import javax.swing.*;

CI

/*

<applet code="JTextFieldDemo" width=300 height=50>


</applet>

*/
public class jtext extends JApplet {
JTextField jtf;

CITSTUDENTS.I
N58

Page

Java/J2EE

06CS753

public void init() {


try {
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
makeGUI();

TS
.IN

}
}
);
} catch (Exception exc) {

EN

System.out.println("Can't create because of " + exc);


}

TU
D

private void makeGUI() {

// Change to flow layout.

getContentPane().setLayout(new FlowLayout());

TS

// Add text field to content pane.


jtf = new JTextField(15);

CI

getContentPane().add(jtf);

jtf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Show text when user presses ENTER.
showStatus(jtf.getText());
}

CITSTUDENTS.I
N59

Page

Java/J2EE

06CS753

});
}
}
4) //Demonstrate JScrollPane.
import java.awt.*;

/*
<applet code="jscroll" width=300 height=250>
</applet>
*/

public void init() {


try {

TU
D

SwingUtilities.invokeAndWait(

EN

public class jscroll extends JApplet {

TS
.IN

import javax.swing.*;

new Runnable() {

public void run() {


makeGUI();

TS

CI

);

} catch (Exception exc) {


System.out.println("Can't create because of " + exc);

}
}

CITSTUDENTS.I
N60

Page

Java/J2EE

06CS753

private void makeGUI() {


// Add 400 buttons to a panel.
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20, 20));
int b = 0;

for(int j = 0; j < 20; j++) {


jp.add(new JButton("Button " + b));
++b;
}

// Create the scroll pane.

EN

TS
.IN

for(int i = 0; i < 20; i++) {

TU
D

JScrollPane jsp = new JScrollPane(jp);

// Add the scroll pane to the content pane.

// Because the default border layout is used,

// the scroll pane will be added to the center.

CI

TS

getContentPane().add(jsp, BorderLayout.CENTER);

5) // Demonstrate JList.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;

CITSTUDENTS.I
N61

Page

Java/J2EE

06CS753

import java.awt.event.*;
/*
<applet code="jlist" width=200 height=120>
</applet>
*/
public class jlist extends JApplet {

TS
.IN

JList jlst;
JLabel jlab;
JScrollPane jscrlp;
// Create an array of cities.

EN

String Cities[] = { "New York", "Chicago", "Houston",


"Denver", "Los Angeles", "Seattle",
"London", "Paris", "New Delhi",

TU
D

"Hong Kong", "Tokyo", "Sydney" };


public void init() {
try {

SwingUtilities.invokeAndWait(

TS

new Runnable() {

public void run() {

CI

makeGUI();

);
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);

CITSTUDENTS.I
N62

Page

Java/J2EE

06CS753

}
}
private void makeGUI() {
// Change to flow layout.
getContentPane().setLayout(new FlowLayout());
// Create a JList.

TS
.IN

jlst = new JList(Cities);

// Set the list selection mode to single-selection.

jlst.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

jscrlp = new JScrollPane(jlst);

EN

// Add the list to a scroll pane.

// Set the preferred size of the scroll pane.

TU
D

jscrlp.setPreferredSize(new Dimension(120, 90));


// Make a label that displays the selection.
jlab = new JLabel("Choose a City");

TS

// Add selection listener for the list.

jlst.addListSelectionListener(new ListSelectionListener() {

CI

public void valueChanged(ListSelectionEvent le) {


// Get the index of the changed item.

int idx = jlst.getSelectedIndex();


// Display selection, if item was selected.
if(idx != -1)
jlab.setText("Current selection: " + Cities[idx]);

CITSTUDENTS.I
N63

Page

Java/J2EE

06CS753

else // Othewise, reprompt.


jlab.setText("Choose a City");

// Add the list and label to the content pane.


getContentPane().add(jscrlp);
getContentPane().add(jlab);

6// Demonstrate JComboBox.


import java.awt.*;

TU
D

import java.awt.event.*;

EN

TS
.IN

});

import javax.swing.*;
/*

TS

<applet code="jcombo" width=300 height=100>


</applet>

CI

*/

public class jcombo extends JApplet {


JLabel jlab;
ImageIcon france, germany, italy, japan;
JComboBox jcb;

CITSTUDENTS.I
N64

Page

Java/J2EE

06CS753

String flags[] = { "France", "Germany", "Italy", "Japan" };


public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {

TS
.IN

public void run() {


makeGUI();
}
}

} catch (Exception exc) {

EN

);

System.out.println("Can't create because of " + exc);

TU
D

}
}

private void makeGUI() {

// Change to flow layout.

TS

getContentPane().setLayout(new FlowLayout());

CI

// Instantiate a combo box and add it to the content pane.


jcb = new JComboBox(flags);

getContentPane().add(jcb);
// Handle selections.
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

CITSTUDENTS.I
N65

Page

Java/J2EE

06CS753

String s = (String) jcb.getSelectedItem();


jlab.setIcon(new ImageIcon(s + ".gif"));
}
});
// Create a label and add it to the content pane.

TS
.IN

jlab = new JLabel(new ImageIcon("france.gif"));


getContentPane().add(jlab);
}

CI

TS

TU
D

EN

CITSTUDENTS.I
N66

Page

06CS753

TS
.IN

Java/J2EE

UNIT-5: JAVA 2 ENTERPRISE EDITION OVERVIEW, DATABASE ACCESS:


Overview of J2EE and J2SE

EN

x Java2 Platform, Enterprise Edition (J2EE) technology provides a componentbased approach to the design, development, assembly, and deployment of
enterprise applications.

TU
D

x The J2EE platform gives you a multitiered distributed application model, the ability
to reuse components, integrated XML-based data interchange, a unified security
model, and flexible transaction control.
x Vendors and customers enjoy the freedom to choose the products and components
that best meet their business and technological requirements.
1. The Concept of JDBC

x The JDBC ( Java Database Connectivity) API defines interfaces and classes for

TS

writing database applications in Java by making database connections.

x Using JDBC you can send SQL, PL/SQL statements to almost any relational

CI

database. JDBC is a Java API for executing SQL statements and supports basic SQL
functionality.

x It provides RDBMS access by allowing you to embed SQL inside Java code.
Overview of JDBC Process
Before you can create a java jdbc connection to the database, you must first import the
java.sql package.

CITSTUDENTS.I
N67

Page

Java/J2EE

06CS753

import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are
to be imported.
Java application calls the JDBC library. JDBC loads a driver which talks to the
database. We can change database engines without changing database code.
Establishing Database Connection and Associating JDBC/ODBC bridge 1.
Loading a database driver,
this step of the jdbc connection process, we load the driver class by calling
Class.forName() with the Driver class name as an argument. Once loaded, the
Driver class creates an instance of itself.

TS
.IN

x In

x A client can connect to Database Server through JDBC Driver. Since most of the
Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is
commonly used.

EN

x The return type of the Class.forName (String ClassName) method is Class. Class is a
class in java.lang package.
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Or any other driver
}

TU
D

catch(Exception x) {

System.out.println( Unable to load the driver class! );


}

2. Creating a oracle jdbc Connection

TS

The JDBC DriverManager class defines objects which can connect Java applications to
a JDBC driver. DriverManager is considered the backbone of JDBC architecture.
DriverManager class manages the JDBC drivers that are installed on the system.

CI

x Its getConnection() method is used to establish a connection to a database. It uses

a username, password, and a jdbc url to establish a connection to the database and
returns a connection object.
x A jdbc Connection represents a session/connection with a specific database. Within
the context of a Connection, SQL, PL/SQL statements are executed and results are
returned. An application can have one or more connections with a single database,
or it can have many connections with different databases.

CITSTUDENTS.I
N68

Page

Java/J2EE

06CS753

x A Connection object provides metadata i.e. information about the database, tables,
and fields. It also contains methods to deal with transactions.
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.
try{

}
catch( SQLException x ){

TS
.IN

Connection dbConnection=DriverManager.getConnection(url,loginName,Pas
sword)

System.out.println( Couldnt get connection! );


}

EN

3. Creating a JDBC Statement object

x Once a connection is obtained we can interact with the database.

TU
D

Connection interface defines methods for interacting with the database via the
established connection.
x To execute SQL statements, you need to instantiate a Statement object from your
connection object by using the createStatement() method.
x Statement statement = dbConnection.createStatement();

TS

x A statement object is used to send and execute SQL statements to a database.


Three kinds of Statements

x Statement: Execute simple sql queries without parameters.

CI

Statement createStatement()
Creates an SQL Statement object.

x Prepared Statement: Execute precompiled sql queries with or without parameters.


Prep aredS tatement prepare Statement(String sql)
returns a new PreparedStatement object. Prep aredStatement objects are
precompiled SQL statements.

CITSTUDENTS.I
N69

Page

Java/J2EE

06CS753

x Callable Statement: Execute a call to a database stored procedure.


CallableStatement prepareCall(String sql)
returns a new CallableStatement object. CallableStatement objects are SQL stored
procedure call statements.
4. Executing a SQL statement with the Statement object, and returning a jdbc
resultSet.

TS
.IN

x Statement interface defines methods that are used to interact with database via
the execution of SQL statements.
x The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute().

For a SELECT statement, the method to use is executeQuery .

For statements that create or modify tables, the method to use is executeUpdate.
Note: Statements that create a table, alter a table, or drop a table are all examples of
DDL statements and are executed with the method executeUpdate. execute()
executes an SQL statement that is written as String object.

EN

TU
D

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. The next() method is used to successively step through the rows of
the tabular results.
ResultSetMetaData Interface holds information on the types and properties of the
columns in a ResultSet. It is constructed from the Connection object.

TS

1) Loading a JDBC Driver: Using Class.forName()


String className = "org.gjt.mm.mysql.Driver";

CI

Class driverObject = Class.forName(className);


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Main {

CITSTUDENTS.I
N70

Page

Java/J2EE

06CS753

public static void main(String[] args) throws Exception {


Connection conn = getHSQLConnection();
Statement st = conn.createStatement();
st.executeUpdate("create table survey (id int,name varchar(30));");
st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
st = conn.createStatement();

TS
.IN

ResultSet rs = st.executeQuery("SELECT * FROM survey");


ResultSetMetaData rsMetaData = rs.getMetaData();

int numberOfColumns = rsMetaData.getColumnCount();

System.out.println("resultSet MetaData column Count=" + numberOfColumns);

EN

rs.close();
st.close();
conn.close();

TU
D

private static Connection getHSQLConnection() throws Exception {


Class.forName("org.hsqldb.jdbcDriver");

String url = "jdbc:hsqldb:mem:data/tutorial";

CI

TS

return DriverManager.getConnection(url, "sa", "");

Using DriverManager.registerDriver()
//String className = "org.gjt.mm.mysql.Driver";

try {
// Registers the given driver with the DriverManager.
DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());

CITSTUDENTS.I
N71

Page

Java/J2EE

06CS753

// here the class is loaded


}
catch (SQLException e) {
e.printStackTrace();
}

public class MainClass {


public static void main(String[] args) {
try {

TS
.IN

To test a JDBC driver installation using Oracle

String className = "oracle.jdbc.driver.OracleDriver";

EN

Class driverObject = Class.forName(className);

System.out.println("driverObject=" + driverObject);

System.out.println("your installation of JDBC Driver OK.");

TU
D

catch (Exception e) {

System.out.println("Failed: JDBC Driver Error: " + e.getMessage());

}
}

TS

CI

2) public class MainClass {


public static void main(String[] args) {
try {

String className = "org.gjt.mm.mysql.Driver";


Class driverObject = Class.forName(className);
System.out.println("driverObject=" + driverObject);
System.out.println("your installation of JDBC Driver OK.");

CITSTUDENTS.I
N72

Page

Java/J2EE

06CS753

} catch (Exception e) {
System.out.println("Failed: JDBC Driver Error: " + e.getMessage());
}
}
}

TS
.IN

3) import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class ms extends Applet implements MouseListener, MouseMotionListener {


String msg = "";

public void init() {


addMouseListener(this);

TU
D

addMouseMotionListener(this);

EN

int mouseX = 0, mouseY = 0; // coordinates of mouse

// Handle mouse clicked.

public void mouseClicked(MouseEvent me) {

TS

// save coordinates
mouseX = 0;

mouseY = 10;

CI

msg = "Mouse clicked.";


repaint();
}

// Handle mouse entered.


public void mouseEntered(MouseEvent me) {
// save coordinates

CITSTUDENTS.I
N73

Page

Java/J2EE

06CS753

mouseX = 0;
mouseY = 10;
msg = "Mouse entered.";
repaint();
}

public void mouseExited(MouseEvent me) {


// save coordinates
mouseX = 0;
mouseY = 10;

repaint();
}

TU
D

// Handle button pressed.

EN

msg = "Mouse exited.";

TS
.IN

// Handle mouse exited.

public void mousePressed(MouseEvent me) {


// save coordinates

mouseX = me.getX();

TS

mouseY = me.getY();
msg = "Down";

CI

repaint();
}

// Handle button released.


public void mouseReleased(MouseEvent me) {

// save coordinates
mouseX = me.getX();

CITSTUDENTS.I
N74

Page

Java/J2EE

06CS753

mouseY = me.getY();
msg = "Up";
repaint();
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {

TS
.IN

// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = "*";

repaint();
}

TU
D

// Handle mouse moved.

EN

showStatus("Dragging mouse at " + mouseX + ", " + mouseY);

public void mouseMoved(MouseEvent me) {


// show status

TS

showStatus("Moving mouse at " + me.getX() + ", " + me.getY());

// Display msg in applet window at current X,Y location.

CI

public void paint(Graphics g) {


g.drawString(msg, mouseX, mouseY);
}

4) // Demonstrate the key event handlers.


import java.awt.*;
import java.awt.event.*;

CITSTUDENTS.I
N75

Page

Java/J2EE

06CS753

import java.applet.*;

public class Key extends Applet implements KeyListener {

String msg = "";

public void init()


{
addKeyListener(this);

EN

requestFocus(); // request input focus

TS
.IN

int X = 10, Y = 20; // output coordinates

TU
D

public void keyPressed(KeyEvent ke)


{

showStatus("Key Down");

TS

public void keyReleased(KeyEvent ke) {

CI

showStatus("Key Up");
}

public void keyTyped(KeyEvent ke)


{
msg += ke.getKeyChar();
repaint();

CITSTUDENTS.I
N76

Page

Java/J2EE

06CS753

}
// Display keystrokes.
public void paint(Graphics g) {
g.drawString(msg, X, Y);
}
}

TS
.IN

5) import java.io.DataInputStream;

class reading
{

EN

public static void main(String arg[])


{

//int intnum=0;

TU
D

DataInputStream in = new DataInputStream(System.in);

//float floatnum=0.0f;

TS

try

System.out.println("Enter an Integer: ");

CI

intnum=Integer.parseInt(in.readLine());
floatnum=Float.valueOf(in.readLine()).floatValue();
}catch(Exception e){}
System.out.println("intnumber= " + intnum);
System.out.println("FloatNumber=" + floatnum);
}

CITSTUDENTS.I
N77

Page

Java/J2EE

06CS753

}
6) class MyThread extends Thread
{
/*MyThread()
{super("My thread");

}*/
public void run()
{
System.out.println("Child thread started");

EN

System.out.println("Child thread terminated");

TS
.IN

start();

TU
D

}
class ThreadDemo
{

TS

public static void main (String args[])

//new MyThread();

CI

MyThread a=new MyThread();

a.start();

System.out.println("Main thread started");


System.out.println("Main thread terminated")

}
7) class A extends Thread

CITSTUDENTS.I
N78

Page

Java/J2EE

06CS753

{
public void run()
{
for(int i=1;i<=5;i++)
{

TS
.IN

if(i==1) yield();
System.out.println("\t From Thread A: i" +i);
}
System.out.println("Exit from A ");

}
class B extends Thread

public void run()


{

TU
D

EN

for(int j=1;j<=5;j++)

TS

CI

System.out.println("\t From Thread B: j" + j);


if(j==3) stop();

System.out.println("Exit from B ");


}
}

CITSTUDENTS.I
N79

Page

Java/J2EE

06CS753

class C extends Thread


{
public void run()
{
for(int k=1;k<=5;k++)

TS
.IN

{
System.out.println("\t From Thread C: k" + k);
if(k==1)
try

sleep(1000);
}

TU
D

catch(Exception e){ }

EN

CI

TS

System.out.println("Exit from C ");

class threadMethod
{

public static void main(String args[])


{
A threadA= new A();

CITSTUDENTS.IN80

Page

Java/J2EE

06CS753

B threadB= new B();


C threadC = new C();
System.out.println("Start thread A");
threadA.start();
System.out.println("Start thread B");

System.out.println("Start thread C");


threadC.start()
System.out.println("End of Main thread ");

}
8) class A extends Thread

public void run()


{

TU
D

EN

TS
.IN

threadB.start();

for(int i=1;i<=4;i++)

TS

System.out.println("\t From Thread A: i" +i);

CI

System.out.println("Exit from A ");

}
}

class B extends Thread


{

CITSTUDENTS.IN81

Page

Java/J2EE

06CS753

public void run()


{
for(int j=1;j<=4;j++)
{
System.out.println("\t From Thread B: j" + j);

System.out.println("Exit from B ");


}
}
class C extends Thread

EN

TS
.IN

public void run()

TU
D

{
for(int k=1;k<=4;k++)
{

System.out.println("\t From Thread C: k" + k);

TS

System.out.println("Exit from C ");

CI

}
}

class threadPriority
{
public static void main(String args[])

CITSTUDENTS.IN82

Page

Java/J2EE

06CS753

{
A threadA = new A();
B threadB = new B();
C threadC = new C();

threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);

threadA.start();

threadB.start();

TU
D

System.out.println("Start thread B");

EN

System.out.println("Start thread A");

TS
.IN

threadC.setPriority(Thread.MAX_PRIORITY);

System.out.println("Start thread C");


threadC.start();

CI

TS

System.out.println("End of main thread");

CITSTUDENTS.IN83

Page

06CS753

EN

TS
.IN

Java/J2EE

Background

TU
D

UNIT -6: SERVLETS

Definition : Servlets are modules of Java code that run in a server application (hence
the name "Servlets", similar to "Applets" on the client side) to answer client requests.

TS

x Servlets are not tied to a specific client-server protocol but they are most commonly
used with HTTP and the word "Servlet" is often used in the meaning of "HTTP
Servlet".

CI

x Servlets make use of the Java standard extension classes in the packages
javax. servlet (the basic Servlet framework) and javax. servlet .http

x Typical uses for HTTP Servlets include:


o Processing and/or storing data submitted by an HTML form.
o Providing dynamic content, e.g. returning the results of a database query to the
client.

CITSTUDENTS.IN84

Page

Java/J2EE

06CS753

o Managing state information on top of the stateless HTTP, e.g. for an online
shopping cart system which manages shopping carts for many concurrent
customers and maps every request to the right customer.

TS
.IN

1. Servlet Life Cycle

The life cycle of a servlet is controlled by the container in which the servlet has been
deployed. When a request is mapped to a servlet, the container performs the following
steps:

a. Loads the servlet class

EN

1. If an instance of the servlet does not exist, the web container:

b. Creates an instance of the servlet class

TU
D

c. Initializes the servlet instance by calling the init method. Initialization is covered
in Initializing a Servlet
2. Invokes the service method, passing a request and response object.
3. If the container needs to remove the servlet, it finalizes the servlet by calling the
servlets destroy method.

TS

1.1 A servlet example

import java.io.*; import javax.servlet.*; import javax.servlet.http. *;

CI

public class HelloClientServlet extends HttpServlet


{

protected void doGet(HttpServletRequest req,

HttpServletResponse res)
throws ServletException, IOException
{

CITSTUDENTS.IN85

Page

Java/J2EE

06CS753

res.setContentType("text/html"); PrintWriter out = res.getWriter();


out.println("<HTML><HEAD><TITLE>Hello Client !</TITLE>"+
"</HEAD><BODY>Hello Client !</BODY></HTML>");
out.close();
}
public String getServletInfo()

TS
.IN

return "HelloClientServlet 1.0 by Stefan Zeiger";


}
}
1.2. Servlet API

EN

x Two packages contain the classes and interfaces that are required to build servlets.
They are javax.servlet and javax.servlet.http.

TU
D

x The javax.servlet and javax.servlet.http packages provide interfaces and classes for
writing servlets. All servlets must implement the Servlet interface, which defines
life cycle methods.
1.3 The servlet packages :

x The javax.servlet package contains a number of classes and interfaces that describe

TS

and define the contracts between a servlet class and the runtime environment
provided for an instance of such a class by a conforming servlet container.

x The Servlet interface is the central abstraction of the servlet API.

CI

x All servlets implement this interface either directly, or more commonly, by


extending a class that implements the interface.

x The two classes in the servlet API that implement the Servlet interface are
GeneriISErvlet and HttpServlet .
x For most purposes, developers will extend HttpServlet to implement their servlets
while implementing web applications employing the HTTP protocol.

CITSTUDENTS.IN86

Page

Java/J2EE

06CS753

x The basic Servlet interface defines a service method for handling client requests. This
method is called for each request that the servlet container routes to an instance of
a servlet.
1.4 Handling HTTP requests and responses :
x Servlets can be used for handling both the GET Requests and the POST Requests.

TS
.IN

x The HttpServlet class is used for handling HTTP GET Requests as it has som
specialized methods that can efficiently handle the HTTP requests. These methods
are;
doGet()
doPost()
doPut()

doDelete() doOptions() doTrace() doHead()

EN

An individual developing servlet for handling HTTP Requests needs to override one
of these methods in order to process the request and generate a response. The servlet is
invoked dynamically when an end-user submits a form.

TU
D

Example:

<form name="F1" action=/servlet/ColServlet> Select the color:


<select name = "col" size = "3">

TS

<option value = "blue">Blue</option> <option value = "orange">Orange</option>


</select>
<input type = "submit" value = "Submit"> </form>

CI

Heres the code for ColServlet.java that overrides the doGet() method to retrieve data
from the HTTP Request and it then generates a response as well.
// import the java packages that are needed for the servlet to work
import java.io .*;

import javax.servlet. *;
import javax.servlet.http. *;
// defining a class

CITSTUDENTS.IN87

Page

Java/J2EE

06CS753

public class ColServlet extends HttpServlet {


public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException, IOException
// request is an object of type HttpServletRequest and it's used to obtain information
// response is an object of type HttpServletResponse and it's used to generate a
response // throws is used to specify the exceptions than a method can throw

String colname = request.getParameter("col");

TS
.IN

// getParameter() method is used to retrieve the selection made by the user


response.setContentType("text/html");
PrintWriter info = response.getWriter();

info .println(col);
info.close();

}
2. Cookies

TU
D

EN

info .println("The color is: ");

TS

Cookies are small bits of textual information that a Web server sends to a browser and
that the browser returns unchanged when visiting the same Web site or domain later.
By having the server read information it sent the client previously, the site can provide
visitors with a number of conveniences like:

CI

x Identifying a user during an e-commerce session..

Avoiding username and password.

Customizing a site.

Focusing advertising.

To send cookies to the client, a servlet would create one or more cookies with the
appropriate names and values via new Cookie (name, value)
2.1 Placing Cookies in the Response Headers

CITSTUDENTS.IN88

Page

Java/J2EE

06CS753

x The cookie is added to the Set-Cookie response header by means of the addCookie
method of HttpServletResponse. For example:
Cookie userCookie = new Cookie("user", "uid 1234");
response.addCookie(userCookie);
x To send cookies to the client, you created a Cookie then used addCookie to send a
Set-Cookie HTTP response header.

TS
.IN

x To read the cookies that come back from the client, call getCookies on the
HttpServletRequest. This returns an array of Cookie objects corresponding to the
values that came in on the Cookie HTTP request header
x Once this array is obtained, loop down it, calling getName on each Cookie until
find one matching the name you have in mind. You then call getValue on the
matching Cookie, doing some processing specific to the resultant value.

String defaultValue) {

EN

public static String getCookieValue(Cookie[] cookies, String cookieName,

for(int i=0; i<cookies.length; i++) {


Cookie cookie = cookies[i];

TU
D

if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
}

TS

return(defaultValue);
}

x Session Tracking

CI

x Why id it needed : In many internet applications it is important to keep track of the


session when the user moves from one page to another or when there are different
users logging on to the same website at the same time

x There are three typical solutions to this problem.


Cookies.
x

HTTP cookies can be used to store information about a shopping session, and

x each subsequent connection can look up the current session and then extract

CITSTUDENTS.IN89

Page

Java/J2EE

06CS753

x information about that session from some location on the server machine.
x

This is an excellent alternative, and is the most widely used approach.

URL Rewriting.
You can append some extra data on the end of each URL that identifies the session,
and the server can associate that session identifier with data it has stored about that
session.

This is also an excellent solution, and even has the advantage that it works with
browsers that don't support cookies or where the user has disabled cookies.

However, it has most of the same problems as cookies, namely that the server-side
program has a lot of straightforward but tedious processing to do. In addition, you
have to be very careful that every URL returned to the user (even via indirect
means like

TS
.IN

x Hidden form fields.

HTML forms have an entry that looks like the following: <INPUT
TYPE="HIDDEN" NAME="session" VALUE="...">.

This means that, when the form is submitted, the specified name and value are
included in the GET or POST data.

This can be used to store information about the session.

TU
D

EN

TS

x However, it has the major disadvantage that it only works if every page is
dynamically generated, since the whole point is that each session has a unique
identifier.
Servlets solution :

CI

x The HttpSession API. is a high-level interface built on top of cookies or URLrewriting. In fact, on many servers, they use cookies if the browser supports
them, but automatically revert to URL-rewriting when cookies are unsupported
or explicitly disabled.
x The servlet author doesn't need to bother with many of the details, doesn't have
to explicitly manipulate cookies or information appended to the URL, and is
automatically given a convenient place to store data that is associated with each
session.

example,

CITSTUDENTS.IN90

Page

Java/J2EE

06CS753

HttpSession session = request.getSession(true); ShoppingCart previousItems =


(ShoppingCart)session.getValue("previousItems"); if (previousItems != null) {
doSomethingWith(previousItems);
} else {
previousItems = new ShoppingCart(...);
doSomethingElseWith(previousItems);

UNIT-7: JSP, RMI

CI

TS

TU
D

EN

TS
.IN

x JavaServer Pages (JSP) is a Sun Microsystems specification for combining Java with
HTML to provide dynamic content forWeb pages.

x When you create dynamic content, JSPs are more convenient to write than HTTP
servlets because they allow to embed Java code directly into HTML pages, in contrast
with HTTP servlets, in which you embed HTML inside Java code.

CITSTUDENTS.IN91

Page

Java/J2EE

06CS753

x JSP is part of the Java 2 Enterprise Edition (J2EE).


x JSP enables to separate the dynamic content of aWeb page from its presentation.
x It caters to two different types of developers: HTML developers, who are responsible
for the graphical design of the page, and Java developers, who handle the
development of software to create the dynamic content.
1. JSP Tags

TS
.IN

The following table describes the basic tags that you can use in a JSP page. Each
shorthand tag has an XML equivalent.
Syntax
<% java_code %>
. . . or use the XML
equivalent:
<jsp:scriptlet>
java_code
</jsp:scriptlet>

<%! declaration %>


. . . or use XML
equivalent...
<jsp:declaration>
declaration;

Description
Embeds Java source code
Scriptlet in yourHTML
page. The Java code is
executed and its output
is inserted in sequence
with the rest
of the HTML in the page.
Directives contain
messages to the
application server.
A directive can also
contain name/value pair
attributes in the form
attr=value, which
provides additional
instructions to
Declares a variable or
method that
can be referenced by
other
declarations, scriptlets,

Directive

<% @ dir-type dir-attr


%>
. . . or use the XML
equivalent:
<jsp:directive.dir_typ
e
dir_attr />

<%= expression %>


. . . or use XML
<jsp:useBean ... >

Defines a Java
that is
Provide access to

TU
D

EN

JSP Tag
Scriptlet

TS

Declarations

CI

Expression

Actions
Tomcat

x Apache Tomcat is an implementation of the Java Servlet and JavaServer Pages


technologies.
x The Java Servlet and JavaServer Pages specifications are developed under the Java
Community Process.

CITSTUDENTS.IN92

Page

Java/J2EE

06CS753

x Apache Tomcat is developed in an open and participatory environment and


released under the Apache Software
Simple example
<% @ page info="a hello world example" %>
<html>
<head><title>Hello, World</title></head>

<% @ include file="dukebanner.html" %>


<table>
<tr>
<td width=150> &nbsp; </td>

TS
.IN

<body bgcolor="#ffffff" background="background.gif">

</table>

TU
D

</body></html>

EN

<td width=250 align=right> <h1>Hello, World !</h1> </td> </tr>

Request string

<%@ page import="hello.NameHandler" %> <jsp:useBean id="mybean"


scope="page"
class="hello.NameHandler" />

TS

<jsp :setProperty name="mybean" property="*" />


<html>

CI

<head><title>Hello, User</title></head>

<body bgcolor="#ffffff" background="background.gif">


<% @ include file="dukebanner.html" %>
<table border="0" width="700">
<tr>
<td width="150"> &nbsp; </td>

CITSTUDENTS.IN93

Page

Java/J2EE

06CS753

<td width="550">
<h1>My name is Duke. What's yours?</h1>
</td> </tr> <tr>
<td width="150" &nbsp; </td>
<td width="550">
<form method="get">

<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</td> </tr> </form>

EN

</table>

TS
.IN

<input type="text" name="username" size="25">

<%

if ( request.getParameter("username") != null ) {

TU
D

%>

<% @ include file="response.jsp" %>


<%
}
%> </body> </html>

TS

The data the user enters is stored in the request object, which usually implements
javax.servlet.HttpServletRequest (or if your implementation uses a different protocol,
another interface that is subclassed from javax.servlet.ServletRequest). You can access
the request object directly within a scriptlet.

CI

Sessions and Cookies in JSP


x In JSP cookie are the object of the class javax.servlet.http.Cookie.
x This class is used to creates a cookie, a small amount of information sent by a
servlet to a Web browser, saved by the browser, and later sent back to the server.
x A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.

CITSTUDENTS.IN94

Page

Java/J2EE

06CS753

The getCookies() method of the request object returns an array of Cookie objects.
Cookies can be constructed using the following code:
<% @ page language="java" import="java.util. *"%> <%
String username=request.getParameter("username"); if(username==null) username="";
Date now = new Date();
String timestamp = now.toString();

TS
.IN

Cookie cookie = new Cookie ("username",username); cookie.setMaxAge(365 * 24 * 60 *


60);
response.addCookie(cookie);
%>
<html> <head>

</head> <body>

EN

<title>Cookie Saved</title>

<p><a href="showcookievaue.jsp">Next Page to view the cookie value</a><p>


</body>

RMI

TU
D

Above code sets the cookie and then displays a link to view cookie page

x RMI applications are often comprised of two separate programs: a server and a
client.

TS

x A typical server application creates a number of remote objects, makes references to


those remote objects accessible, and waits for clients to invoke methods on those
remote objects.

CI

x A typical client application gets a remote reference to one or more remote objects in
the server and then invokes methods on them. RMI provides the mecahnism by
which the server and the client communicate and pass information back and forth.
Such an applications is sometimes referred to as a distributed object application.
The java.rmi.Remote Interface :

In RMI, a remote interface is an interface that declares a set of methods that may be
invoked from a remote Java virtual machine. A remote interface must satisfy the
following requirements:

CITSTUDENTS.IN95

Page

Java/J2EE

06CS753

A remote interface must at least extend, either directly or indirectly, the interface
java.rmi.Remote.
Each method declaration in a remote interface must satisfy the requirements
Server side and Client side
The interface ServerRef represents the server-side handle for a remote object
implementation.

public interface ServerRef extends RemoteRef {

TS
.IN

package java.rmi.server;

RemoteStub exportObject(java.rmi.Remote obj, Object data) throws


java.rmi.RemoteException;
String getClientHost() throws ServerNotActiveException; }

x The method exportObject finds or creates a client stub object for the

EN

supplied Remote object implementation obj.

TU
D

x The parameter data contains information necessary to export the object (such as
port number).
x The method getClientHost returns the host name of the current client.
When called from a thread actively handling a remote method invocation, the
host name of the client invoking the call is returned.

TS

x If a remote method call is not currently being service, then


ServerNotActiveException is called.

CI

There is no special configuration necessary to enable the client to send RMI calls
through a firewall. The client can, however, disable the packaging of RMI calls as
HTTP requests by setting the java.rmi.server.disableHttp property to equal the
boolean value true.

PROGRAMS

1) listing 1
// Use a BufferedReader to read characters from the console.
import java.io.*;

CITSTUDENTS.IN96

Page

Java/J2EE

06CS753

class BRRead {
public static void main(String args[])
throws IOException
{
char c;

TS
.IN

BufferedReader br = new

BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");

do {
c = (char) br.read();

TU
D

System.out.println(c);

EN

// read characters

} while(c != 'q');
}

TS

listing 2

CI

// Read a string from console using a BufferedReader.


import java.io.*;

class BRReadLines {
public static void main(String args[])
throws IOException

CITSTUDENTS.IN97

Page

Java/J2EE

06CS753

{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

System.out.println("Enter lines of text.");


System.out.println("Enter 'stop' to quit.");
do {
str = br.readLine();

} while(!str.equals("stop"));

listing 3
// A tiny editor.

TS

import java.io.*;

TU
D

EN

System.out.println(str);

TS
.IN

String str;

CI

class TinyEdit {

public static void main(String args[])


throws IOException

{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new

CITSTUDENTS.IN98

Page

Java/J2EE

06CS753
InputStreamReader(System.in));

String str[] = new String[100];

System.out.println("Enter lines of text.");


System.out.println("Enter 'stop' to quit.");

str[i] = br.readLine();
if(str[i].equals("stop")) break;
}

// display the lines

TU
D

for(int i=0; i<100; i++) {

EN

System.out.println("\nHere is your file:");

TS
.IN

for(int i=0; i<100; i++) {

if(str[i].equals("stop")) break;
System.out.println(str[i]);

CI

TS

listing 4

// Demonstrate System.out.write().
class WriteDemo {
public static void main(String args[]) {
int b;

CITSTUDENTS.IN99

Page

Java/J2EE

06CS753

b = 'A';
System.out.write(b);
System.out.write('\n');
}

TS
.IN

listing 5
// Demonstrate PrintWriter

public class PrintWriterDemo {

EN

import java.io.*;

public static void main(String args[]) {

TU
D

PrintWriter pw = new PrintWriter(System.out, true);


pw.println("This is a string");
int i = -7;
pw.println(i);

TS

double d = 4.5e-7;
pw.println(d);

CI

}
}

listing 6
/* Display a text file.

CITSTUDENTS.IN100

Page

Java/J2EE

06CS753

To use this program, specify the name


of the file that you want to see.
For example, to see a file called TEST.TXT,
use the following command line.

java ShowFile TEST.TXT

TS
.IN

*/

import java.io.*;

EN

class ShowFile {
public static void main(String args[])

{
int i;

TU
D

throws IOException

FileInputStream fin;

TS

try {

fin = new FileInputStream(args[0]);

CI

} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;

} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;

CITSTUDENTS.IN101

Page

Java/J2EE

06CS753

// read characters until EOF is encountered


do {
i = fin.read();
if(i != -1) System.out.print((char) i);

TS
.IN

} while(i != -1);

fin.close();
}

listing 7

TU
D

/* Copy a text file.

EN

To use this program, specify the name

of the source file and the destination file.

TS

For example, to copy a file called FIRST.TXT

to a file called SECOND.TXT, use the following

CI

command line.

java CopyFile FIRST.TXT SECOND.TXT

*/

import java.io.*;

CITSTUDENTS.IN102

Page

Java/J2EE

06CS753

class CopyFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;

TS
.IN

FileOutputStream fout;

try {
// open input file

EN

try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {

return;
}

TU
D

System.out.println("Input File Not Found");

TS

// open output file


try {

CI

fout = new FileOutputStream(args[1]);


} catch(FileNotFoundException e) {
System.out.println("Error Opening Output File");
return;
}
} catch(ArrayIndexOutOfBoundsException e) {

CITSTUDENTS.IN103

Page

Java/J2EE

06CS753

System.out.println("Usage: CopyFile From To");


return;
}

// Copy File
try {

TS
.IN

do {
i = fin.read();
if(i != -1) fout.write(i);
} while(i != -1);

System.out.println("File Error");

fin.close();
fout.close();

TS

TU
D

EN

} catch(IOException e) {

CI

listing 8

import java.awt.*;

import java.applet.*;

public class SimpleApplet extends Applet {


public void paint(Graphics g) {

CITSTUDENTS.IN104

Page

Java/J2EE

06CS753

g.drawString("A Simple Applet", 20, 20);


}
}

listing 9
import java.awt.*;

TS
.IN

import java.applet.*;
/*

<applet code="SimpleApplet" width=200 height=60>


</applet>

EN

*/

public class SimpleApplet extends Applet {

TU
D

public void paint(Graphics g) {

g.drawString("A Simple Applet", 20, 20);


}

TS

listing 10

CI

// Demonstrate instanceof operator.


class A {
int i, j;

class B {

CITSTUDENTS.IN105

Page

Java/J2EE

06CS753

int i, j;
}

class C extends A {
int k;

TS
.IN

class D extends A {
int k;

class InstanceOf {

EN

A a = new A();
B b = new B();
C c = new C();

TS

D d = new D();

TU
D

public static void main(String args[]) {

if(a instanceof A)

CI

System.out.println("a is instance of A");


if(b instanceof B)

System.out.println("b is instance of B");

if(c instanceof C)
System.out.println("c is instance of C");
if(c instanceof A)

CITSTUDENTS.IN106

Page

Java/J2EE

06CS753

System.out.println("c can be cast to A");

if(a instanceof C)
System.out.println("a can be cast to C");

// compare types of derived types


A ob;

EN

ob = d; // A reference to d

TS
.IN

System.out.println();

System.out.println("ob now refers to d");


if(ob instanceof D)

TU
D

System.out.println("ob is instance of D");

System.out.println();

TS

ob = c; // A reference to c

CI

System.out.println("ob now refers to c");

if(ob instanceof D)
System.out.println("ob can be cast to D");

else
System.out.println("ob cannot be cast to D");

CITSTUDENTS.IN107

Page

Java/J2EE

06CS753

if(ob instanceof A)
System.out.println("ob can be cast to A");

System.out.println();

if(a instanceof Object)


System.out.println("a may be cast to Object");
if(b instanceof Object)
System.out.println("b may be cast to Object");

EN

if(c instanceof Object)

TS
.IN

// all objects can be cast to Object

System.out.println("c may be cast to Object");


if(d instanceof Object)

}
}

TS

listing 11

TU
D

System.out.println("d may be cast to Object");

// A simple example that uses a native method.

CI

public class NativeDemo {


int i;

public static void main(String args[]) {


NativeDemo ob = new NativeDemo();

ob.i = 10;

CITSTUDENTS.IN108

Page

Java/J2EE

06CS753

System.out.println("This is ob.i before the native method:" +


ob.i);
ob.test(); // call a native method
System.out.println("This is ob.i after the native method:" +
ob.i);

// declare native method


public native void test() ;

// load DLL that contains static method

EN

static {

TS
.IN

System.loadLibrary("NativeDemo");

listing 12

TU
D

/* This file contains the C version of the

CI

*/

TS

test() method.

#include <jni.h>

#include "NativeDemo.h"
#include <stdio.h>

JNIEXPORT void JNICALL Java_NativeDemo_test(JNIEnv *env, jobject obj)

CITSTUDENTS.IN109

Page

Java/J2EE

06CS753

{
jclass cls;
jfieldID fid;
jint i;

cls = (*env)->GetObjectClass(env, obj);


fid = (*env)->GetFieldID(env, cls, "i", "I");

if(fid == 0) {

EN

printf("Could not get field id.\n");

TS
.IN

printf("Starting the native method.\n");

return;
}

TU
D

i = (*env)->GetIntField(env, obj, fid);


printf("i = %d\n", i);

(*env)->SetIntField(env, obj, fid, 2*i);

TS

printf("Ending the native method.\n");

CI

listing 13

// Demonstrate assert.
class AssertDemo {
static int val = 3;

// Return an integer.

CITSTUDENTS.IN110

Page

Java/J2EE

06CS753

static int getnum() {


return val--;
}

public static void main(String args[])


{

TS
.IN

int n;

for(int i=0; i < 10; i++) {

EN

n = getnum();

assert n > 0; // will fail with n is 0

TU
D

System.out.println("n is " + n);


}
}

TS

listing 14

CI

// A poor way to use assert!!!


class AssertDemo {

// get a random number generator

static int val = 3;

// Return an integer.

CITSTUDENTS.IN111

Page

Java/J2EE

06CS753

static int getnum() {


return val--;
}

public static void main(String args[])


{

TS
.IN

int n = 0;

for(int i=0; i < 10; i++) {

}
}
}

TS

listing 15

TU
D

System.out.println("n is " + n);

EN

assert (n = getnum()) > 0; // This is not a good idea!

// Compute the hypotenuse of a right triangle.

CI

class Hypot {

public static void main(String args[]) {


double side1, side2;
double hypot;

side1 = 3.0;

CITSTUDENTS.IN112

Page

Java/J2EE

06CS753

side2 = 4.0;

// Notice how sqrt() and pow() must be qualified by


// their class name, which is Math.
hypot = Math.sqrt(Math.pow(side1, 2) +

System.out.println("Given sides of lengths " +


side1 + " and " + side2 +
" the hypotenuse is " +

EN

hypot);

TS
.IN

Math.pow(side2, 2));

listing 16

TU
D

// Use static import to bring sqrt() and pow() into view.


import static java.lang.Math.sqrt;

TS

import static java.lang.Math.pow;

CI

// Compute the hypotenuse of a right triangle.


class Hypot {

public static void main(String args[]) {


double side1, side2;
double hypot;

CITSTUDENTS.IN113

Page

Java/J2EE

06CS753

side1 = 3.0;
side2 = 4.0;

// Here, sqrt() and pow() can be called by themselves,


// without their class name.

System.out.println("Given sides of lengths " +


side1 + " and " + side2 +
" the hypotenuse is " +

EN

hypot);

TS
.IN

hypot = sqrt(pow(side1, 2) + pow(side2, 2));

CI

TS

TU
D

CITSTUDENTS.IN114

Page

06CS753

EN

UNIT 8: ENTERPRISE JAVA BEANS

TS
.IN

Java/J2EE

Definition : Enterprise JavaBeans (EJB) is a managed, server-side component


architecture for modular construction of enterprise applications.

TU
D

In a typical J2EE application, Enterprise JavaBeans (EJBs) contain the application's


business logic and live business data. Although it is possible to use standard Java
objects to contain your business logic and business data, using EJBs addresses
many of the issues you would find by using simple Java objects, such as scalability,
lifecycle management, and state management.
There are three different types of EJB that are suited to different purposes:
Session EJBA Session EJB is useful for mapping business process flow (or
equivalent application concepts). There are two sub-types of Session EJB
stateless and stateful represent "pure" functionality that is created as it is needed.

Entity EJBAn Entity EJB maps a combination of data (or equivalent


application concept) and associated functionality. Entity EJBs are usually based
on an underlying data store and will be created based on that data within it.

Message-driven EJBA Message-driven EJB is very similar in concept to a


Session EJB, but is only activated when an asynchronous message arrives.

CI

TS
x

1. Deployment Descriptors

CITSTUDENTS.IN115

Page

Java/J2EE

06CS753

Definition : A deployment descriptor is a file that defines the following kinds of


information: EJB structural information, such as the EJB name, class, home and
remote interfaces, bean type (session or entity), environment entries, resource factory
references, EJB references, security role references, as well as additional information
based on the bean type. Application assembly information, such as EJB references,
security roles, security role references, method permissions, and container transaction
attributes. Specifying assembly descriptor information is an optional task that an
Application Assembler performs.

TS
.IN

1.1 Session Bean


Session bean is a type of enterprise bean; a type of EJB server-side component.

x Session bean components implement the javax.ejb.SessionBean interface and can be


stateless or stateful.

EN

x Stateless session beans are components that perform transient services; stateful
session beans are components that are dedicated to one client and act as a serverside extension of that client.

TU
D

Session beans can act as agents modeling workflow or provide access to special
transient business services. As an agent, a stateful session bean might represent a
customer's session at an online shopping site.
As a transitive service, a stateless session bean might provide access to validate
and process credit card orders.

x Session beans do not normally represent persistent business concepts like Employee
or Order. This is the domain of a different component type called an entity bean.

TS

Example : package ejb.demo;


import javax.ejb.*;

CI

import java.rmi.Remote;
import java.rmi.RemoteException; import java.util. *;

/* *

* This interface is extremely simple it declares only * one create method.


*/
public interface DemoHome extends EJBHome {

CITSTUDENTS.IN116

Page

Java/J2EE

06CS753

public Demo create() throws CreateException, RemoteException;


}
Entity Java Bean
x

An entity bean represents a business object in a persistent storage mechanism.

Some examples of business objects are customers, orders, and products.

In the J2EE SDK, the persistent storage mechanism is a relational database.

TS
.IN

x
Typically, each entity bean has an underlying table in a relational database, and
each instance of the bean corresponds to a row in that table.
Message-Driven Bean

A message-driven bean is an enterprise bean that allows J2EE applications to process


messages asynchronously.

It acts as a JMS message listener, which is similar to an event listener except that it
receives messages instead of events.

EN

TU
D

x The messages may be sent by any J2EE component--an application client, another
enterprise bean, or a Web component--or by a JMS application or system that does
not use J2EE technology.
Message-driven beans currently process only JMS messages, but in the future they may
be used to process other kinds of messages
The JAR file

TS

The Java Archive (JAR) file format enables you to bundle multiple files into a single
archive file. Typically a JAR file contains the class files and auxiliary resources associated
with applets and applications.

CI

The JAR file format provides many benefits:


x

Security: You can digitally sign the contents of a JAR file. Users who recognize
your signature can then optionally grant your software security privileges it
wouldn't otherwise have.

Decreased download time: If your applet is bundled in a JAR file, the applet's class
files and associated resources can be downloaded to a browser in a single HTTP
transaction without the need for opening a new connection for each file.

CITSTUDENTS.IN117

Page

Java/J2EE
x

06CS753

Compression: The JAR format allows you to compress your files for efficient
storage.

x Packaging for extensions: The extensions framework provides a means by which you
can add functionality to the Java core platform, and the JAR file format defines the
packaging for extensions. By using the JAR file format, you can turn your software
into extensions as well.

TS
.IN

x Package Sealing: Packages stored in JAR files can be optionally sealed so that the
package can enforce version consistency. Sealing a package within a JAR file
means that all classes defined in that package must be found in the same JAR file.
Package Versioning: A JAR file can hold data about the files it contains, such as
vendor and version information.

TU
D

EN

x Portability: The mechanism for handling JAR files is a standard part of the Java
platform's core API.

TS

PROGRAMS
listing 1
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/

CI

public class AppletSkel extends Applet {


// Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start() {
// start or resume execution

CITSTUDENTS.IN118

Page

Java/J2EE

06CS753

}
// Called when the applet is stopped.
public void stop() {
// suspends execution
}

TS
.IN

/* Called when applet is terminated. This is the last


method executed. */
public void destroy() {
// perform shutdown activities
}

// Called when an applet's window must be restored.


public void paint(Graphics g) {
// redisplay contents of window
}

listing 2
public void update(Graphics g) {
// redisplay your window, here.
}

TU
D

public void paint(Graphics g) {


update(g);
}

EN

CI

TS

listing 3
/* A simple applet that sets the foreground and
background colors and outputs a string. */
import java.awt.*;
import java.applet.*;
/*
<applet code="Sample" width=300 height=50>
</applet>
*/
public class Sample extends Applet{
String msg;
// set the foreground and background colors.
public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init( ) --";

CITSTUDENTS.IN119

Page

Java/J2EE

06CS753

}
// Initialize the string to be displayed.
public void start() {
msg += " Inside start( ) --";
}

TS
.IN

// Display msg in applet window.


public void paint(Graphics g) {
msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
}
listing 4
/* A simple banner applet.

TU
D

EN

This applet creates a thread that scrolls


the message contained in msg right to left
across the applet's window.
*/
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleBanner" width=300 height=50>
</applet>
*/

TS

public class SimpleBanner extends Applet implements Runnable {


String msg = " A Simple Moving Banner.";
Thread t = null;
int state;
boolean stopFlag;

CI

// Set colors and initialize thread.


public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
}
// Start thread
public void start() {
t = new Thread(this);
stopFlag = false;
t.start();
}

CITSTUDENTS.IN120

Page

Java/J2EE

06CS753

// Display banner
for( ; ; ) {
try { repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());
msg += ch;
if(stopFlag)
break;
} catch(InterruptedException e) {}
}

// Pause the banner.


public void stop() {
stopFlag = true;
t = null;
}

TU
D

// Display the banner.


public void paint(Graphics g) {
g.drawString(msg, 50, 30);
}

EN

TS
.IN

// Entry point for the thread that runs the banner.


public void run() {
char ch;

CI

TS

listing 5
// Using the Status Window.
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.

CITSTUDENTS.IN121

Page

Java/J2EE

06CS753

public void paint(Graphics g) {


g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}

TU
D

EN

public class ParamDemo extends Applet{


String fontName;
int fontSize;
float leading;
boolean active;

TS
.IN

listing 6
// Use Parameters
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/

// Initialize the string to be displayed.


public void start() {
String param;

TS

fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";

CI

param = getParameter("fontSize");
try {
if(param != null) // if not found
fontSize = Integer.parseInt(param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;
}
param = getParameter("leading");
try {
if(param != null) // if not found

CITSTUDENTS.IN122

Page

Java/J2EE

06CS753

leading = Float.valueOf(param).floatValue();
else
leading = 0;
} catch(NumberFormatException e) {
leading = -1;
}
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();

// Display parameters.
public void paint(Graphics g) {
g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
g.drawString("Leading: " + leading, 0, 42);
g.drawString("Account Active: " + active, 0, 58);
}

EN

TS
.IN

TU
D

listing 7
// A parameterized banner
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamBanner" width=300 height=50>
<param name=message value="Java makes the Web move!">
</applet>
*/

CI

TS

public class ParamBanner extends Applet implements Runnable {


String msg;
Thread t = null;
int state;
boolean stopFlag;
// Set colors and initialize thread.
public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
}
// Start thread
public void start() {
msg = getParameter("message");

CITSTUDENTS.IN123

Page

Java/J2EE

06CS753

if(msg == null) msg = "Message not found.";


msg = " " + msg;
t = new Thread(this);
stopFlag = false;
t.start();
}

EN

// Display banner
for( ; ; ) {
try {
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());
msg += ch;
if(stopFlag)
break;
} catch(InterruptedException e) {}
}

TS
.IN

// Entry point for the thread that runs the banner.


public void run() {
char ch;

TU
D

}
// Pause the banner.
public void stop() {
stopFlag = true;
t = null;
}

CI

TS

// Display the banner.


public void paint(Graphics g) {
g.drawString(msg, 50, 30);
}

listing 8
// Display code and document bases.
import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code="Bases" width=300 height=50>
</applet>
*/

CITSTUDENTS.IN124

Page

Java/J2EE

06CS753

public class Bases extends Applet{


// Display code and document bases.
public void paint(Graphics g) {
String msg;
URL url = getCodeBase(); // get code base
msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);

}
}

EN

listing 9
/* Using an applet context, getCodeBase(),
and showDocument() to display an HTML file.
*/

TS
.IN

url = getDocumentBase(); // get document base


msg = "Document base: " + url.toString();
g.drawString(msg, 10, 40);

TU
D

import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code="ACDemo" width=300 height=50>
</applet>
*/

TS

public class ACDemo extends Applet{


public void start() {
AppletContext ac = getAppletContext();
URL url = getCodeBase(); // get url of this applet

CI

try {
ac.showDocument(new URL(url+"Test.html"));
} catch(MalformedURLException e) {
showStatus("URL not found");
}

}
}
2) listing 1
// Demonstrate Labels
import java.awt.*;
import java.applet.*;
/*

CITSTUDENTS.IN125

Page

Java/J2EE

06CS753

<applet code="LabelDemo" width=300 height=200>


</applet>
*/
public class LabelDemo extends Applet {
public void init() {
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");

TS
.IN

// add labels to applet window


add(one);
add(two);
add(three);
}
}

TU
D

EN

listing 2
// Demonstrate Buttons
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/

public class ButtonDemo extends Applet implements ActionListener {


String msg = "";
Button yes, no, maybe;

CI

TS

public void init() {


yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);

yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {

CITSTUDENTS.IN126

Page

Java/J2EE

06CS753

String str = ae.getActionCommand();


if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
else if(str.equals("No")) {
msg = "You pressed No.";
}
else {
msg = "You pressed Undecided.";
}

TS
.IN

repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
}
}

TU
D

EN

listing 3
// Recognize Button objects.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonList" width=250 height=150>
</applet>
*/

TS

public class ButtonList extends Applet implements ActionListener {


String msg = "";
Button bList[] = new Button[3];

CI

public void init() {


Button yes = new Button("Yes");
Button no = new Button("No");
Button maybe = new Button("Undecided");
// store references to buttons as added
bList[0] = (Button) add(yes);
bList[1] = (Button) add(no);
bList[2] = (Button) add(maybe);
// register to receive action events
for(int i = 0; i < 3; i++) {
bList[i].addActionListener(this);

CITSTUDENTS.IN127

Page

Java/J2EE

06CS753

}
}

TS
.IN

public void actionPerformed(ActionEvent ae) {


for(int i = 0; i < 3; i++) {
if(ae.getSource() == bList[i]) {
msg = "You pressed " + bList[i].getLabel();
}
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg, 6, 100);
}
}

TU
D

EN

listing 4
// Demonstrate check boxes.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CheckboxDemo" width=250 height=200>
</applet>
*/

public class CheckboxDemo extends Applet implements ItemListener {


String msg = "";
Checkbox winXP, winVista, solaris, mac;

CI

TS

public void init() {


winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
add(solaris);
add(mac);

winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);

CITSTUDENTS.IN128

Page

Java/J2EE

06CS753

}
public void itemStateChanged(ItemEvent ie) {
repaint();
}

TS
.IN

// Display current state of the check boxes.


public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac OS: " + mac.getState();
g.drawString(msg, 6, 160);
}

EN

TU
D

listing 5
// Demonstrate check box group.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CBGroup" width=250 height=200>
</applet>
*/

CI

TS

public class CBGroup extends Applet implements ItemListener {


String msg = "";
Checkbox winXP, winVista, solaris, mac;
CheckboxGroup cbg;
public void init() {
cbg = new CheckboxGroup();
winXP = new Checkbox("Windows XP", cbg, true);
winVista = new Checkbox("Windows Vista", cbg, false);
solaris = new Checkbox("Solaris", cbg, false);
mac = new Checkbox("Mac OS", cbg, false);
add(winXP);
add(winVista);
add(solaris);

CITSTUDENTS.IN129

Page

Java/J2EE

06CS753

add(mac);
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}

// Display current state of the check boxes.


public void paint(Graphics g) {
msg = "Current selection: ";
msg += cbg.getSelectedCheckbox().getLabel();
g.drawString(msg, 6, 100);
}

EN

TS
.IN

public void itemStateChanged(ItemEvent ie) {


repaint();
}

TU
D

listing 6
// Demonstrate Choice lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ChoiceDemo" width=300 height=180>
</applet>
*/

TS

public class ChoiceDemo extends Applet implements ItemListener {


Choice os, browser;
String msg = "";

CI

public void init() { os =


new Choice(); browser =
new Choice();

// add items to os list


os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");

CITSTUDENTS.IN130

Page

Java/J2EE

06CS753

browser.add("Firefox");
browser.add("Opera");
// add choice lists to window
add(os);
add(browser);
// register to receive item events
os.addItemListener(this);
browser.addItemListener(this);

public void itemStateChanged(ItemEvent ie) {


repaint();
}

TU
D

EN

// Display current selections.


public void paint(Graphics g) {
msg = "Current OS: ";
msg += os.getSelectedItem();
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);
}

TS
.IN

CI

TS

listing 7
// Demonstrate Lists.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ListDemo" width=300 height=180>
</applet>
*/
public class ListDemo extends Applet implements ActionListener {
List os, browser;
String msg = "";
public void init() {
os = new List(4, true);
browser = new List(4, false);
// add items to os list

CITSTUDENTS.IN131

Page

Java/J2EE

06CS753

os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
// add items to browser list
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");

// add lists to window


add(os);
add(browser);
// register to receive action events
os.addActionListener(this);
browser.addActionListener(this);

EN

TS
.IN

browser.select(1);

TU
D

public void actionPerformed(ActionEvent ae) {


repaint();
}
// Display current selections.
public void paint(Graphics g) {
int idx[];

CI

TS

msg = "Current OS: ";


idx = os.getSelectedIndexes();
for(int i=0; i<idx.length; i++)
msg += os.getItem(idx[i]) + " ";
g.drawString(msg, 6, 120);
msg = "Current Browser: ";
msg += browser.getSelectedItem();
g.drawString(msg, 6, 140);

listing 8
// Demonstrate scroll bars.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*

CITSTUDENTS.IN132

Page

Java/J2EE

06CS753

<applet code="SBDemo" width=300 height=200>


</applet>
*/
public class SBDemo extends Applet
implements AdjustmentListener, MouseMotionListener {
String msg = "";
Scrollbar vertSB, horzSB;

TS
.IN

public void init() {


int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));

EN

vertSB = new Scrollbar(Scrollbar.VERTICAL,


0, 1, 0, height);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,
0, 1, 0, width);
add(vertSB);
add(horzSB);
// register to receive adjustment events
vertSB.addAdjustmentListener(this);
horzSB.addAdjustmentListener(this);

TU
D

addMouseMotionListener(this);

public void adjustmentValueChanged(AdjustmentEvent ae) {


repaint();
}

CI

TS

// Update scroll bars to reflect mouse dragging.


public void mouseDragged(MouseEvent me) {
int x = me.getX();
int y = me.getY();
vertSB.setValue(y);
horzSB.setValue(x);
repaint();
}
// Necessary for MouseMotionListener
public void mouseMoved(MouseEvent me) {
}

// Display current value of scroll bars.


public void paint(Graphics g) {

CITSTUDENTS.IN133

Page

Java/J2EE

06CS753

msg = "Vertical: " + vertSB.getValue();


msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 6, 160);
// show current mouse drag position
g.drawString("*", horzSB.getValue(),
vertSB.getValue());
}
}

TS
.IN

listing 9
// Demonstrate text field.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*

EN

<applet code="TextFieldDemo" width=380 height=150>


</applet>
*/
public class TextFieldDemo extends Applet
implements ActionListener {

TU
D

TextField name, pass;

TS

public void init() {


Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
pass.setEchoChar('?');

CI

add(namep);
add(name);
add(passp);
add(pass);

// register to receive action events


name.addActionListener(this);
pass.addActionListener(this);

}
// User pressed Enter.
public void actionPerformed(ActionEvent ae) {
repaint();

CITSTUDENTS.IN134

Page

Java/J2EE

06CS753

}
public void paint(Graphics g) {
g.drawString("Name: " + name.getText(), 6, 60);
g.drawString("Selected text in name: "
+ name.getSelectedText(), 6, 80);
g.drawString("Password: " + pass.getText(), 6, 100);
}
}

TS
.IN

listing 10
// Demonstrate TextArea.
import java.awt.*;
import java.applet.*;
/*
<applet code="TextAreaDemo" width=300 height=250>
</applet>
*/

TS

TU
D

EN

public class TextAreaDemo extends Applet {


public void init() {
String val =
"Java SE 6 is the latest version of the most\n" +
"widely-used computer language for Internet programming,\n" +
"Building on a rich heritage, Java has advanced both\n" +
"the art and science of computer language design.\n\n" +
"One of the reasons for Java's ongoing success is its\n" +
"constant, steady rate of evolution. Java has never stood\n" +
"still. Instead, Java has consistently adapted to the\n" +
"rapidly changing landscape of the networked world.\n" +
"Moreover, Java has often led the way, charting the\n" +
"course for others to follow.";
TextArea text = new TextArea(val, 10, 30);
add(text);

CI

listing 11
// Use left-aligned flow layout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="FlowLayoutDemo" width=250 height=200>
</applet>

CITSTUDENTS.IN135

Page

Java/J2EE

06CS753

*/
public class FlowLayoutDemo extends Applet
implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;

TS
.IN

public void init() {


// set left-aligned flow layout
setLayout(new FlowLayout(FlowLayout.LEFT));

add(winXP);
add(winVista);
add(solaris);
add(mac);

TU
D

// register to receive item events


winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);

EN

winXP = new Checkbox("Windows XP", null, true);


winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");

TS

// Repaint when status of a check box changes.


public void itemStateChanged(ItemEvent ie) {
repaint();
}

CI

// Display current state of the check boxes.


public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();

CITSTUDENTS.IN136

Page

Java/J2EE

06CS753

g.drawString(msg, 6, 160);
}
}

public class BorderLayoutDemo extends Applet {


public void init() {
setLayout(new BorderLayout());

TS
.IN

listing 12
// Demonstrate BorderLayout.
import java.awt.*;
import java.applet.*;
import java.util.*;
/*
<applet code="BorderLayoutDemo" width=400 height=200>
</applet>
*/

TU
D

EN

add(new Button("This is across the top."),


BorderLayout.NORTH);
add(new Label("The footer message might go here."),
BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);

TS

String msg = "The reasonable man adapts " +


"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
"
- George Bernard Shaw\n\n";

add(new TextArea(msg), BorderLayout.CENTER);


}

CI

listing 13
// Demonstrate BorderLayout with insets.
import java.awt.*;
import java.applet.*;
import java.util.*;
/*
<applet code="InsetsDemo" width=400 height=200>
</applet>
*/

CITSTUDENTS.IN137

Page

Java/J2EE

06CS753

public class InsetsDemo extends Applet {


public void init() {
// set background color so insets can be easily seen
setBackground(Color.cyan);
setLayout(new BorderLayout());

EN

String msg = "The reasonable man adapts " +


"himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" +
"
- George Bernard Shaw\n\n";

TS
.IN

add(new Button("This is across the top."),


BorderLayout.NORTH);
add(new Label("The footer message might go here."),
BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);

TU
D

add(new TextArea(msg), BorderLayout.CENTER);


}
// add insets
public Insets getInsets() {
return new Insets(10, 10, 10, 10);
}

CI

TS

listing 14
// Demonstrate GridLayout
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=300 height=200>
</applet>
*/
public class GridLayoutDemo extends Applet {
static final int n = 4;
public void init() {
setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));

CITSTUDENTS.IN138

Page

Java/J2EE

06CS753

for(int i = 0; i < n; i++) {


for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
}
}
}
}

EN

TS
.IN

listing 15
// Demonstrate CardLayout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="CardLayoutDemo" width=300 height=100>
</applet>
*/
public class CardLayoutDemo extends Applet
implements ActionListener, MouseListener {

TU
D

Checkbox winXP, winVista, solaris, mac;


Panel osCards;
CardLayout cardLO;
Button Win, Other;

TS

public void init() {


Win = new Button("Windows");
Other = new Button("Other");
add(Win);
add(Other);

CI

cardLO = new CardLayout();


osCards = new Panel();
osCards.setLayout(cardLO); // set panel layout to card layout
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
// add Windows check boxes to a panel
Panel winPan = new Panel();

CITSTUDENTS.IN139

Page

Java/J2EE

06CS753

winPan.add(winXP);
winPan.add(winVista);
// Add other OS check boxes to a panel
Panel otherPan = new Panel();
otherPan.add(solaris);
otherPan.add(mac);

// add cards to main applet panel


add(osCards);

// register mouse events


addMouseListener(this);
}

EN

// register to receive action events


Win.addActionListener(this);
Other.addActionListener(this);

TS
.IN

// add panels to card deck panel


osCards.add(winPan, "Windows");
osCards.add(otherPan, "Other");

TU
D

// Cycle through panels.


public void mousePressed(MouseEvent me) {
cardLO.next(osCards);
}

CI

TS

// Provide empty implementations for the other MouseListener methods.


public void mouseClicked(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
}
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == Win) {
cardLO.show(osCards, "Windows");
}
else {
cardLO.show(osCards, "Other");
}

CITSTUDENTS.IN140

Page

Java/J2EE

06CS753

}
}

public class GridBagDemo extends Applet


implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;

TS
.IN

listing 16
// Use GridBagLayout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="GridBagDemo" width=250 height=200>
</applet>
*/

EN

public void init() {


GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbag);

TU
D

// Define check boxes.


winXP = new Checkbox("Windows XP ", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");

TS

// Define the grid bag.

CI

// Use default row weight of 0 for first row.


gbc.weightx = 1.0; // use a column weight of 1
gbc.ipadx = 200; // pad by 200 units
gbc.insets = new Insets(4, 4, 0, 0); // inset slightly from top left
gbc.anchor = GridBagConstraints.NORTHEAST;

gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(winXP, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(winVista, gbc);
// Give second row a weight of 1.

CITSTUDENTS.IN141

Page

Java/J2EE

06CS753

gbc.weighty = 1.0;
gbc.gridwidth = GridBagConstraints.RELATIVE;
gbag.setConstraints(solaris, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbag.setConstraints(mac, gbc);

TS
.IN

// Add the components.


add(winXP);
add(winVista);
add(solaris);
add(mac);
// Register to receive item events.
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);

EN

TU
D

// Repaint when status of a check box changes.


public void itemStateChanged(ItemEvent ie) {
repaint();
}

CI

TS

// Display current state of the check boxes.


public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();
g.drawString(msg, 6, 160);
}

listing 17
// Illustrate menus.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

CITSTUDENTS.IN142

Page

Java/J2EE

06CS753

/*
<applet code="MenuDemo" width=250 height=250>
</applet>
*/

MenuFrame(String title) {
super(title);
// create menu bar and add it to frame
MenuBar mbar = new MenuBar();
setMenuBar(mbar);

TU
D

EN

// create the menu items


Menu file = new Menu("File");
MenuItem item1, item2, item3, item4, item5;
file.add(item1 = new MenuItem("New..."));
file.add(item2 = new MenuItem("Open..."));
file.add(item3 = new MenuItem("Close"));
file.add(item4 = new MenuItem("-"));
file.add(item5 = new MenuItem("Quit..."));
mbar.add(file);

TS
.IN

// Create a subclass of Frame


class MenuFrame extends Frame {
String msg = "";
CheckboxMenuItem debug, test;

TS

Menu edit = new Menu("Edit"); MenuItem


item6, item7, item8, item9; edit.add(item6 =
new MenuItem("Cut")); edit.add(item7 =
new MenuItem("Copy")); edit.add(item8 =
new MenuItem("Paste")); edit.add(item9 =
new MenuItem("-"));

CI

Menu sub = new Menu("Special"); MenuItem


item10, item11, item12; sub.add(item10 = new
MenuItem("First")); sub.add(item11 = new
MenuItem("Second")); sub.add(item12 = new
MenuItem("Third")); edit.add(sub);
// these are checkable menu items
debug = new CheckboxMenuItem("Debug");
edit.add(debug);
test = new CheckboxMenuItem("Testing");
edit.add(test);

CITSTUDENTS.IN143

Page

Java/J2EE

06CS753

mbar.add(edit);

EN

TS
.IN

// create an object to handle action and item events


MyMenuHandler handler = new MyMenuHandler(this);
// register it to receive those events
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
item11.addActionListener(handler);
item12.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);

TU
D

// create an object to handle window events


MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);

public void paint(Graphics g) {


g.drawString(msg, 10, 200);

TS

if(debug.getState())
g.drawString("Debug is on.", 10, 220);
else
g.drawString("Debug is off.", 10, 220);

CI

if(test.getState())
g.drawString("Testing is on.", 10, 240);
else
g.drawString("Testing is off.", 10, 240);

}
class MyWindowAdapter extends WindowAdapter {
MenuFrame menuFrame;
public MyWindowAdapter(MenuFrame menuFrame) {
this.menuFrame = menuFrame;

CITSTUDENTS.IN144

Page

Java/J2EE

06CS753

}
public void windowClosing(WindowEvent we) {
menuFrame.setVisible(false);
}
}

CI

TS

TU
D

EN

TS
.IN

class MyMenuHandler implements ActionListener, ItemListener {


MenuFrame menuFrame;
public MyMenuHandler(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
// Handle action events
public void actionPerformed(ActionEvent ae) {
String msg = "You selected ";
String arg = ae.getActionCommand();
if(arg.equals("New..."))
msg += "New.";
else if(arg.equals("Open..."))
msg += "Open.";
else if(arg.equals("Close"))
msg += "Close.";
else if(arg.equals("Quit..."))
msg += "Quit.";
else if(arg.equals("Edit"))
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))
msg += "Second.";
else if(arg.equals("Third"))
msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();
}
// Handle item events
public void itemStateChanged(ItemEvent ie) {

CITSTUDENTS.IN145

Page

Java/J2EE

06CS753

menuFrame.repaint();
}
}
// Create frame window.
public class MenuDemo extends Applet {
Frame f;

setSize(new Dimension(width, height));


f.setSize(width, height);
f.setVisible(true);

public void start() {


f.setVisible(true);
}

TU
D

public void stop() {


f.setVisible(false);
}

EN

TS
.IN

public void init() {


f = new MenuFrame("Menu Demo");
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));

CI

TS

listing 18
// Demonstrate Dialog box.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="DialogDemo" width=250 height=250>
</applet>
*/
// Create a subclass of Dialog.
class SampleDialog extends Dialog implements ActionListener {
SampleDialog(Frame parent, String title) {
super(parent, title, false);
setLayout(new FlowLayout());
setSize(300, 200);
add(new Label("Press this button:"));

CITSTUDENTS.IN146

Page

Java/J2EE

06CS753

Button b;
add(b = new Button("Cancel"));
b.addActionListener(this);
}

public void paint(Graphics g) {


g.drawString("This is in the dialog box", 10, 70);
}
}

MenuFrame(String title) {
super(title);

EN

// Create a subclass of Frame.


class MenuFrame extends Frame {
String msg = "";
CheckboxMenuItem debug, test;

TS
.IN

public void actionPerformed(ActionEvent ae) {


dispose();
}

TU
D

// create menu bar and add it to frame


MenuBar mbar = new MenuBar();
setMenuBar(mbar);

CI

TS

// create the menu items Menu file =


new Menu("File"); MenuItem item1,
item2, item3, item4;
file.add(item1 = new MenuItem("New..."));
file.add(item2 = new MenuItem("Open..."));
file.add(item3 = new MenuItem("Close"));
file.add(new MenuItem("-"));
file.add(item4 = new MenuItem("Quit..."));
mbar.add(file);
Menu edit = new Menu("Edit"); MenuItem
item5, item6, item7; edit.add(item5 = new
MenuItem("Cut")); edit.add(item6 = new
MenuItem("Copy")); edit.add(item7 = new
MenuItem("Paste")); edit.add(new
MenuItem("-"));
Menu sub = new Menu("Special", true);
MenuItem item8, item9, item10;
sub.add(item8 = new MenuItem("First"));

CITSTUDENTS.IN147

Page

Java/J2EE

06CS753

sub.add(item9 = new MenuItem("Second"));


sub.add(item10 = new MenuItem("Third"));
edit.add(sub);
// these are checkable menu items
debug = new CheckboxMenuItem("Debug");
edit.add(debug);
test = new CheckboxMenuItem("Testing");
edit.add(test);

TS
.IN

mbar.add(edit);

TU
D

EN

// create an object to handle action and item events


MyMenuHandler handler = new MyMenuHandler(this);
// register it to receive those events
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);

TS

// create an object to handle window events


MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);

CI

}
public void paint(Graphics g) {
g.drawString(msg, 10, 200);
if(debug.getState())
g.drawString("Debug is on.", 10, 220);
else
g.drawString("Debug is off.", 10, 220);
if(test.getState())
g.drawString("Testing is on.", 10, 240);
else
g.drawString("Testing is off.", 10, 240);
}

CITSTUDENTS.IN148

Page

Java/J2EE

06CS753

TS
.IN

class MyWindowAdapter extends WindowAdapter {


MenuFrame menuFrame;
public MyWindowAdapter(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
public void windowClosing(WindowEvent we) {
menuFrame.dispose();
}
}

CI

TS

TU
D

EN

class MyMenuHandler implements ActionListener, ItemListener {


MenuFrame menuFrame;
public MyMenuHandler(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
// Handle action events
public void actionPerformed(ActionEvent ae) {
String msg = "You selected ";
String arg = ae.getActionCommand();
// Activate a dialog box when New is selected.
if(arg.equals("New...")) {
msg += "New."; SampleDialog d = new
SampleDialog(menuFrame, "New Dialog Box");
d.setVisible(true);
}
// Try defining other dialog boxes for these options.
else if(arg.equals("Open..."))
msg += "Open.";
else if(arg.equals("Close"))
msg += "Close.";
else if(arg.equals("Quit..."))
msg += "Quit.";
else if(arg.equals("Edit"))
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))

CITSTUDENTS.IN149

Page

Java/J2EE

06CS753

}
public void itemStateChanged(ItemEvent ie) {
menuFrame.repaint();
}
}
// Create frame window.
public class DialogDemo extends Applet {
Frame f;

TS
.IN

msg += "Second.";
else if(arg.equals("Third"))
msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();

TU
D

setSize(width, height);

EN

public void init() {


f = new MenuFrame("Menu Demo");
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));

f.setSize(width, height);
f.setVisible(true);
}

TS

public void start() {


f.setVisible(true);
}

CI

public void stop() {


f.setVisible(false);
}

listing 19
/* Demonstrate File Dialog box.

This is an application, not an applet.


*/
import java.awt.*;
import java.awt.event.*;

CITSTUDENTS.IN150

Page

Java/J2EE

06CS753

// Create a subclass of Frame


class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);

TS
.IN

// Remove the window when closed.


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}

EN

// Demonstrate FileDialog.
class FileDialogDemo {
public static void main(String args[]) {
// Create a frame that owns the dialog.
Frame f = new SampleFrame("File Dialog Demo");
f.setVisible(true);
f.setSize(100, 100);

TU
D

FileDialog fd = new FileDialog(f, "File Dialog");


fd.setVisible(true);
}
}

CI

TS

listing 20
/*
* <applet code=ButtonDemo2 width=200 height=100>
* </applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ButtonDemo2 extends Applet {
MyButton myButton;
static int i = 0;
public void init() {
myButton = new MyButton("Test Button");
add(myButton);
}

CITSTUDENTS.IN151

Page

Java/J2EE

06CS753

class MyButton extends Button {


public MyButton(String label) {
super(label);
enableEvents(AWTEvent.ACTION_EVENT_MASK);
}
protected void processActionEvent(ActionEvent ae) {
showStatus("action event: " + i++);
super.processActionEvent(ae);
}
}

TS
.IN

EN

listing 21
/*
* <applet code=CheckboxDemo2 width=300 height=100>
* </applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

CI

TS

TU
D

public class CheckboxDemo2 extends Applet {


MyCheckbox myCheckbox1, myCheckbox2, myCheckbox3;
public void init() {
myCheckbox1 = new MyCheckbox("Item 1");
add(myCheckbox1);
myCheckbox2 = new MyCheckbox("Item 2");
add(myCheckbox2);
myCheckbox3 = new MyCheckbox("Item 3");
add(myCheckbox3);
}
class MyCheckbox extends Checkbox {
public MyCheckbox(String label) {
super(label);
enableEvents(AWTEvent.ITEM_EVENT_MASK);
}
protected void processItemEvent(ItemEvent ie) {
showStatus("Checkbox name/state: " + getLabel() +
"/" + getState());
super.processItemEvent(ie);
}
}
}
listing 22
/*

CITSTUDENTS.IN152

Page

Java/J2EE

06CS753

* <applet code=CheckboxGroupDemo2 width=300 height=100>


* </applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

TS

TU
D

EN

TS
.IN

public class CheckboxGroupDemo2 extends Applet {


CheckboxGroup cbg;
MyCheckbox myCheckbox1, myCheckbox2, myCheckbox3;
public void init() {
cbg = new CheckboxGroup();
myCheckbox1 = new MyCheckbox("Item 1", cbg, true);
add(myCheckbox1);
myCheckbox2 = new MyCheckbox("Item 2", cbg, false);
add(myCheckbox2);
myCheckbox3 = new MyCheckbox("Item 3", cbg, false);
add(myCheckbox3);
}
class MyCheckbox extends Checkbox {
public MyCheckbox(String label, CheckboxGroup cbg,
boolean flag) {
super(label, cbg, flag);
enableEvents(AWTEvent.ITEM_EVENT_MASK);
}
protected void processItemEvent(ItemEvent ie) {
showStatus("Checkbox name/state: " + getLabel() +
"/" + getState());
super.processItemEvent(ie);
}
}
}

CI

listing 23
/*
* <applet code=ChoiceDemo2 width=300 height=100>
* </applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class ChoiceDemo2 extends Applet {


MyChoice choice;
public void init() {
choice = new MyChoice();

CITSTUDENTS.IN153

Page

Java/J2EE

06CS753

choice.add("Red");
choice.add("Green");
choice.add("Blue");
add(choice);

TS
.IN

}
class MyChoice extends Choice { public MyChoice()
{ enableEvents(AWTEvent.ITEM_EVENT_MASK);
}
protected void processItemEvent(ItemEvent ie) {
showStatus("Choice selection: " + getSelectedItem());
super.processItemEvent(ie);
}
}
}

EN

listing 24
/*
* <applet code=ListDemo2 width=300 height=100>
* </applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

CI

TS

TU
D

public class ListDemo2 extends Applet {


MyList list;
public void init() {
list = new MyList();
list.add("Red");
list.add("Green");
list.add("Blue");
add(list);
}
class MyList extends List { public MyList() {
enableEvents(AWTEvent.ITEM_EVENT_MASK |
AWTEvent.ACTION_EVENT_MASK);
}
protected void processActionEvent(ActionEvent ae) {
showStatus("Action event: " + ae.getActionCommand());
super.processActionEvent(ae);
}
protected void processItemEvent(ItemEvent ie) {
showStatus("Item event: " + getSelectedItem());
super.processItemEvent(ie);

CITSTUDENTS.IN154

Page

Java/J2EE

06CS753

}
}
}

TS
.IN

listing 25
/*
* <applet code=ScrollbarDemo2 width=300 height=100>
* </applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

CI

TS

TU
D

EN

public class ScrollbarDemo2 extends Applet {


MyScrollbar myScrollbar;
public void init() {
myScrollbar = new MyScrollbar(Scrollbar.HORIZONTAL,
0, 1, 0, 100);
add(myScrollbar);
}
class MyScrollbar extends Scrollbar {
public MyScrollbar(int style, int initial, int thumb,
int min, int max) {
super(style, initial, thumb, min, max);
enableEvents(AWTEvent.ADJUSTMENT_EVENT_MASK);
}
protected void processAdjustmentEvent(AdjustmentEvent ae) {
showStatus("Adjustment event: " + ae.getValue());
setValue(getValue());
super.processAdjustmentEvent(ae);
}
}
}

CITSTUDENTS.IN155

Page