Java
Java
pdf
Unit2and3_user interface with swing.pdf
Unit4Database Connectivity.pdf
Unit5Network Programming.pdf
Unit6Java Beans.pdf
Unit7Servlets and JSP.pdf
Unit8RMI and CORBA.pdf
Class
The class is at the core of Java. It is the logical construct upon which the entire Java language is
built because it defines the shape and nature of an object. As such,the class forms the basis for
object-oriented programming in Java. Any concept you wish to implement in a Java program
must be encapsulated within a class.
Perhaps the most important thing to understand about a class is that it defines a
new data type. Once defined, this new type can be used to create objects of that type.
Thus, a class is a template for an object, and an object is an instance of a class. Because an
object is an instance of a class, you will often see the two words object and instance used
interchangeably.
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method1
}
type methodname2(parameter-list) {
// body of method2
}
// ...
type methodnameN(parameter-list) {
// body of methodN
}
}
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a
class are called members of the class.
Example of Class
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
// sets dimensions of box
Creating Objects
When you create a class, you are creating a new data type. You can use this type to
declare objects of that type. However, obtaining objects of a class is a two-step process.
First, you must declare a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object. Second, you must
acquire an actual, physical copy of the object and assign it to that variable. You can do
this using the new operator. The new operator dynamically allocates (that is, allocates at
run time) memory for an object and returns a reference to it. This reference is, more or
less, the address in memory of the object allocated by new.This reference is then stored in
the variable. Thus, in Java, all class objects must be dynamically allocated.
Constructors
Java allows objects to initialize themselves when they are created. This automatic
class Box {
double width;
double height;
double depth;
Overloading Methods
In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case,
the methods are said to be overloaded, and the process is referred to as method
overloading. Method overloading is one of the ways that Java implements
polymorphism.
When an overloaded method is invoked, Java uses the type and/or number of arguments
as its guide to determine which version of the overloaded method to actually call. Thus,
overloaded methods must differ in the type and/or number of their parameters. While
overloaded methods may have different return types, the return type alone is insufficient
to distinguish two versions of a method. When Java encounters a call to an overloaded
method, it simply executes the version of the method whose parameters match the
arguments used in the call.
Overloading Constructors
In addition to overloading normal methods, one can also overload constructors.
The most common example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist. Instance variables declared as static
are, essentially, global variables. When objects of its class are declared, no copy of a
static variable is made. Instead, all instances of the class share the same static variable.
static {
System.out.println("Static block initialized.");
b = a * 4;
}
As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set
to 3, then the static block executes (printing a message), and finally, b is initialized to a *
4 or 12. Then main( ) is called, which calls meth( ), passing 42 to x. The three println( )
statements refer to the two static variables a and b, as well as to the local variable x.
Outside of the class in which they are defined, static methods and variables can be used
independently of any object. To do so, you need only specify the name of their class
followed by the dot operator.
classname.method( )
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Final Variables
A variable can be declared as final. Doing so prevents its contents from being modified.
This means that you must initialize a final variable when it is declared.
(In this usage, final is similar to const in C/C++/C#.) For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
Arrays
In Java Arrays are implemented as objects.
class Length {
public static void main(String args[ ]) {
int a1[ ] = new int[10];
int a2[ ] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[ ] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
Inheritance
Inheritance is one of the cornerstones of object-oriented programming because it allows
the creation of hierarchical classifications. Using inheritance, you can create a general
class that defines traits common to a set of related items. This class can then be inherited
by other, more specific classes, each adding those things that are unique to it. In the
terminology of Java, a class that is inherited is called a superclass. The class that does
the inheriting is called a subclass. Therefore, a subclass is a specialized version of a
superclass. It inherits all of the instance variables and methods defined by the superclass
and adds its own, unique elements.
To inherit a class, you simply incorporate the definition of one class into another by using
the extends keyword.
// Create a superclass.
class A {
int i, j;
void showij( ) {
System.out.println("i and j: " + i + " " + j);
}
}
class SimpleInheritance {
public static void main(String args[ ]) {
A superOb = new A( );
As you can see, the subclass B includes all of the members of its superclass, A. This is
why subOb can access i and j and call showij( ). Also, inside sum( ), i and j can be
referred to directly, as if they were part of B.
Note:Although a subclass includes all of the members of its superclass, it cannot access
those members of the superclass that have been declared as private.
Super Keyword
super has two general forms.
The first calls the superclass’ constructor.
The second is used to access a member of the superclass that has been hidden by a
member of a subclass.
Example
class Box {
private double width;
private double height;
private double depth;
// default constructor
BoxWeight() {
super();
weight = -1;
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2,3);
subOb.show();
}
}
Package
Packages are containers for classes that are used to keep the class name space
compartmentalized. For example, a package allows you to create a class named List,
which you can store in your own package without concern that it will collide with some
other class named List stored elsewhere. Packages are stored in a hierarchical manner and
are explicitly imported into new class definitions.
The package is both a naming and a visibility control mechanism. You can define
classes inside a package that are not accessible by code outside that package. You can
also define class members that are only exposed to other members of the same
package.This allows your classes to have intimate knowledge of each other, but not
expose that knowledge to the rest of the world.
Defining a package
package pkg_name;
Here,package is a keyword and pkg_name is the name of the package. For example, the
following statement creates a package called MyPackage.
package MyPackage;
In Java a hierarchy of packages can be created. To do so, simply separate each package
name from the one above it by use of a period. The general form of a multileveled
package statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of Java development system. For
example, a package declared as
Access Modifiers
The three access specifiers, private, public, and protected, provide a variety of ways to
produce the many levels of access required by these categories. Table below sums up the
interactions
An Access Example
public Protection() {
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
package p1;
class Derived extends Protection {
Derived() {
System.out.println("derived constructor");
Prepared by: Navin K. Sharma 15 Java Unit 1
System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
Importing Packages
Classes within packages must be fully qualified with their package name or names.It
could become tedious to type in the long dot-separated package path name for every class
you want to use. For this reason, Java includes the import statement to bring certain
classes, or entire packages, into visibility. Once imported, a class can be referred to
directly, using only its name.
The import statement is a convenience to the programmer and is not technically needed to
write a complete Java program. If you are going to refer to a few dozen classes in your
application, however, the import statement will save a lot of typing.
In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions. This is the general form of the
import statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate
package inside the outer package separated by a dot (.). There is no practical limit on the
depth of a package hierarchy, except that imposed by the file system. Finally, you specify
import java.util.Date;
import java.io.*;
Any place you use a class name, you can use its fully qualified name, which includes its
full package hierarchy. For example, this fragment uses an import statement:
import java.util.*;
class MyDate extends Date {
}
The same example without the import statement looks like this:
class MyDate extends java.util.Date {
}
NOTE: When a package is imported, only those items within the package declared as
public will be available to non-subclasses in the importing code.
For example, if you want the Balance class of the package MyPack to be available as a
stand-alone class for general use outside of MyPack, then you will need to declare it as
public and put it into its own file, as shown here:
package MyPack;
/* Now, the Balance class, its constructor, and its
show() method are public. This means that they can
be used by non-subclass code outside their package.
*/
public class Balance {
String name;
double bal;
As you can see, the Balance class is now public. Also, its constructor and its show()
method are public, too. This means that they can be accessed by any type of code outside
the MyPack package. For example, here TestBalance imports MyPack and is then able
to make use of the Balance class:
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}
Experiment- Remove the public specifier from the Balance class and then try compiling
TestBalance. As explained, errors will result.
Interfaces
Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body. In practice, this means that you can define
interfaces which don’t make assumptions about how they are implemented. Once it is
defined, any number of classes can implement an interface. Also, one class can
implement any number of interfaces.
Using interface, you can specify what a class must do, but not how it does it.
To implement an interface, a class must create the complete set of methods defined by the
interface. However, each class is free to determine the details of its own implementation.
By providing the interface keyword, Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism. Interfaces are designed to support dynamic
method resolution at run time. Normally, in order for a method to be called from one
class to another, both classes need to be present at compile time so the Java compiler can
check to ensure that the method signatures are compatible.
Defining an Interface
An interface is defined much like a class. This is the general form of an interface:
Here, access is either public or not used. When no access specifier is included, then
default access results, and the interface is only available to other members of the package
in which it is declared. When it is declared as public, the interface can be used by any
other code. name is the name of the interface, and can be any valid identifier.
Notice that the methods which are declared have no bodies. They end with a semicolon
after the parameter list. They are, essentially, abstract methods; there can be no default
implementation of any method specified within an interface. Each class that includes an
interface must implement all of the methods.
Variables can be declared inside of interface declarations. They are implicitly final and
static, meaning they cannot be changed by the implementing class. They must also be
initialized with a constant value. All methods and variables are implicitly public if the
interface, itself, is declared as public.
Implementing Interface
interface Callback {
void callback(int param);
}
--Save this file as Callback.java
void nonIfaceMeth() {
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
class TestIface {
public static void main(String args[ ]) {
Client ob1 = new Client();
AnotherClient ob2 = new AnotherClient();
ob1.callback(42);
ob2.callback(42);
}
}
Exception-Handling
An exception is an abnormal condition that arises in a code sequence at run time. In
other words, an exception is a run-time error. In computer languages that do not
support exception handling, errors must be checked and handled manually—typically
through the use of error codes, and so on. This approach is as cumbersome as it is
troublesome.Java’s exception handling avoids these problems and, in the process, brings
run-time error management into the object-oriented world.
Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally. Briefly, here is how they work. Program statements that you want to monitor for
exceptions are contained within a try block. If an exception occurs within the try block, it
is thrown. Your code can catch this exception (using catch) and handle it in some rational
manner. System-generated exceptions are automatically thrown by the Java run-time
system. To manually throw an exception, use the keyword throw. Any exception that is
thrown out of a method must be specified as such by a throws clause. Any code that
absolutely must be executed before a method returns is put in a finally block.
try {
Uncaught Exceptions
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a new
exception object and then throws this exception. This causes the execution of Exc0 to
stop, because once an exception has been thrown, it must be caught by an exception
handler and dealt with immediately. In this example, we haven’t supplied any exception
handlers of our own, so the exception is caught by the default handler provided by the
Java run-time system.
Notice that the call to println( ) inside the try block is never executed. Once an exception
is thrown, program control transfers out of the try block into the catch block.
Put differently, catch is not “called,” so execution never “returns” to the try block from a
catch. Thus, the line “This will not be printed.” is not displayed. Once the catch statement
has executed, program control continues with the next line in the program following the
entire try/catch mechanism
The goal of most well-constructed catch clauses should be to resolve the exceptional
condition and then continue on as if the error had never happened.
For example, in the next program each iteration of the for loop obtains two random
integers. Those two integers are divided by each other, and the result is used to divide the
value 12345. The final result is put into a. If either division operation causes a divide-by-
zero error, it is caught, the value of a is set to zero, and the program continues.
throw
So far, you have only been catching exceptions that are thrown by the Java run-time
system. However, it is possible for your program to throw an exception explicitly, using
the throw statement. You can throw exceptions yourself by using the throw statement.
The general form of throw is :
throw ThrowableInstance;
The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed. The nearest enclosing try block is inspected to see if it has
a catch statement that matches the type of the exception. If it does find a match, control is
transferred to that statement. If not, then the next enclosing try statement is inspected, and
so on. If no matching catch is found, then the default exception handler halts the program
and prints the stack trace.
Here is a sample program that creates and throws an exception. The handler that catches
the exception rethrows it to the outer handler.
// Demonstrate throw.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
throws
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. You
do this by including a throws clause in the method’s declaration. A throws clause lists the
types of exceptions that a method might throw.
This is the general form of a method declaration that includes a throws clause:
Example
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
finally
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path
that alters the normal flow through the method. Depending upon how the method is
coded, it is even possible for an exception to cause the method to return prematurely.
This could be a problem in some methods. For example, if a method opens a file upon
finally creates a block of code that will be executed after a try/catch block has completed
and before the code following the try/catch block. The finally block will execute whether
or not an exception is thrown. If an exception is thrown, the finally block will execute
even if no catch statement matches the exception. Any time a method is about to return to
the caller from inside a try/catch block, via an uncaught exception or an explicit return
statement, the finally clause is also executed just before the method returns. This can be
useful for closing file handles and freeing up any other resources that might have
been allocated at the beginning of a method with the intent of disposing of them
before returning.
Each try statement requires at least one catch or a finally clause.
Here is an example program that shows three methods that exit in various ways, none
without executing their finally clauses:
// Demonstrate finally.
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
Multithreading
Unlike most other computer languages, Java provides built-in support for multithreaded
programming. A multithreaded program contains two or more parts that can run
concurrently. Each part of such a program is called a thread, and each thread defines a
separate path of execution. Thus, multithreading is a specialized form of multitasking.
Multitasking threads require less overhead than multitasking processes. Processes are
heavyweight tasks that require their own separate address spaces. Interprocess
communication is expensive and limited. Context switching from one process to another
is also costly. Threads, on the other hand, are lightweight. They share the same address
space and cooperatively share the same heavyweight process. Interthread communication
is inexpensive, and context switching from one thread to the next is low cost.
Multithreading enables to write very efficient programs that make maximumn use of the
CPU, because idle time can be kept to a minimum.
Although the main thread is created automatically when program is started, it can be
controlled through a Thread object. To do so, you must obtain a reference to it by calling
the method currentThread( ), which is a public static member of Thread. It general form
is shown here:
The sleep( ) method causes the thread from which it is called to suspend execution for
the specified period of milliseconds. Its general form is shown here:
static void sleep(long milliseconds) throws InterruptedException
The number of milliseconds to suspend is specified in milliseconds. This method may
throw an InterruptedException.
Creating a Thread
In the most general sense, you create a thread by instantiating an object of type Thread.
Java defines two ways in which this can be accomplished:
■ You can implement the Runnable interface.
■ You can extend the Thread class, itself.
The following two sections look at each method, in turn.
Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable
interface. Runnable abstracts a unit of executable code. You can construct a thread on any
object that implements Runnable. To implement Runnable, a class need only implement a
single method called run( ), which is declared like this:
public void run( )
Inside run( ), you will define the code that constitutes the new thread. It is important to
understand that run( ) can call other methods, use other classes, and declare variables, just
like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of
type Thread from within that class.
After the new thread is created, it will not start running until you call its start( ) method,
which is declared within Thread. In essence, start( ) executes a call to run( ).
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Passing this as the first argument indicates that you want the new thread to call the run( )
method on this object. Next, start( ) is called, which starts the thread of execution
beginning at the run( ) method. This causes the child thread’s for loop to begin. After
calling start( ), NewThread’s constructor returns to main( ). When the main thread
resumes, it enters its for loop. Both threads continue running, sharing the CPU, until their
loops finish.
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
As you can see, once started, all three child threads share the CPU. Notice the call
to sleep(10000) in main( ). This causes the main thread to sleep for ten seconds
and ensures that it will finish last.
class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new NewThread("Three");
As you can see, after the calls to join( ) return, the threads have stopped
executing.
Synchronization
When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by which
this is achieved is called synchronization. As you will see, Java provides unique,
language-level support for it.
NOTE-Since the Call method is not synchronized more than one thread can access this method
simultenously and result in the Race Condition.
To prevent from the race condition precede the call() with the keyword
synchronized and analyze the output.
class Callme {
synchronized void call(String msg) {
................................
}
After synchronized has been added to call( ), the output of the program is as follows:
[Hello]
[Synchronized]
[World]
To bring data into a program, a Java program opens a stream to a data source, such as a file or
remote socket, and reads the information serially. On the flip side, a program can open a stream
to a data source and write to it in a serial fashion. Whether you are reading from a file or from a
socket, the concept of serially reading from, and writing to different data sources is the same. For
that very reason, once you understand the top level classes (java.io.Reader, java.io.Writer), the
remaining classes are straightforward to work with.
Prior to JDK 1.1, the input and output classes (mostly found in the java.io package) only
supported 8-bit byte streams. The concept of 16-bit Unicode character streams was introduced
in JDK 1.1. While byte streams were supported via the java.io.InputStream and
java.io.OutputStream classes and their subclasses, character streams are implemented by the
java.io.Reader and java.io.Writer classes and their subclasses.
Most of the functionality available for byte streams is also provided for character streams. The
Unless you are working with binary data, such as image and sound files, you should use
readers and writers (character streams) to read and write information for the following
reasons:
They can handle any character in the Unicode character set (while the byte streams are
limited to ISO-Latin-1 8-bit bytes).
They are easier to internationalize because they are not dependent upon a specific
character encoding.
They use buffering techniques internally and are therefore potentially much more
efficient than byte streams.
Reading Characters
To read a character from a BufferedReader, use read( ). The version of read( ) that we will be
using is
int read( ) throws IOException
Each time that read( ) is called, it reads a character from the input stream and returns it as an
integer value. It returns –1 when the end of the stream is encountered. As you can see, it can
throw an IOException.
The following program demonstrates read( ) by reading characters from the console until
the user types a “q”:
class BRRead {
public static void main(String args[])
throws IOException
{
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
Reading Strings
To read a string from the keyboard, use the version of readLine( ) that is a member of the
BufferedReader class. Its general form is shown here:
String readLine( ) throws IOException
As you can see, it returns a String object.
The following program demonstrates BufferedReader and the readLine( ) method to read
from the console.It creates an array of String objects and then reads in lines of text, storing
each line in the array. It will read up to 100 lines or until you enter “stop”.
import java.io.*;
class TinyEdit {
File I/O
The Byte Streams
The byte stream classes provide a rich environment for handling byte-oriented I/O. A byte
stream can be used with any type of object, including binary data. This versatility makes byte
streams important to many types of programs. It contains two main abstract classess
InputStream and OutputStream.
InputStream
InputStream is an abstract class that defines Java’s model of streaming byte input. All of the
methods in this class will throw an IOException on error conditions. Below are the list of the
methods in InputStream :
OutputStream
OutputStream is an abstract class that defines streaming byte output. All of the methods in this
class return a void value and throw an IOException in the case of errors. Table below shows the
methods in OutputStream
Method Description
void close( ) Closes the output stream. Further write
attempts will generate an IOException.
void flush( ) Finalizes the output state so that any
buffers are cleared. That is, it flushes the
output buffers.
void write(int b) Writes a single byte to an output stream.
Note that the parameter is an int, which
allows you to call write( ) with expressions
without having to cast them back to byte.
void write(byte buffer[ ]) Writes a complete array of bytes to an
output stream.
FileInputStream
The FileInputStream class creates an InputStream that you can use to read bytes from a file.
Its two most common constructors are shown here:
FileInputStream(String filepath)
FileInputStream(File fileObj)
Either can throw a FileNotFoundException. Here, filepath is the full path name of a file, and
fileObj is a File object that describes the file.
The following example creates two FileInputStreams that use the same disk file and each of the
two constructors:
FileInputStream f0 = new FileInputStream("D:\abc.txt")
File f = new File("D:\abc.txt");
FileInputStream f1 = new FileInputStream(f);
Although the first constructor is probably more commonly used, the second allows us to closely
examine the file using the File methods, before we attach it to an input stream. When a
FileInputStream is created, it is also opened for reading.
The example below shows how to read a single byte, an array of bytes, and a subrange array of
bytes. It also illustrates how to use available( ) to determine the number of bytes remaining, and
how to use the skip( ) method to skip over unwanted bytes. The program reads its own source
file, which must be in the current directory.
// Demonstrate FileInputStream.
import java.io.*;
class FileInputStreamDemo {
public static void main(String args[]) throws Exception {
int size;
InputStream f = new FileInputStream("FileInputStreamDemo.java");
System.out.println("Total Available Bytes: " + (size = f.available()));
int n = size/40;
System.out.println("First " + n + " bytes of the file one read() at a time");
for (int i=0; i < n; i++) {
System.out.print((char) f.read());
}
System.out.println("\nStill Available: " + f.available());
System.out.println("Reading the next " + n + " with one read(b[ ])");
byte b[] = new byte[n];
if (f.read(b) != n) {
System.err.println("couldn't read " + n + " bytes.");
}
System.out.println(new String(b, 0, n));
System.out.println("\nStill Available: " + (size = f.available()));
FileOutputStream
FileOutputStream creates an OutputStream that you can use to write bytes to a file. Its most
commonly used constructors are shown here:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
They can throw a FileNotFoundException or a SecurityException. Here, filePath is the full path
name of a file, and fileObj is a File object that describes the file. If append is true, the file is
opened in append mode. The fourth constructor was added by Java 2, version 1.4.
Creation of a FileOutputStream is not dependent on the file already existing. FileOutputStream
will create the file before opening it for output when you create the object. In the case where you
attempt to open a read-only file, an IOException will be thrown.
// Demonstrate FileOutputStream.
import java.io.*;
class FileOutputStreamDemo {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good men\n"
+ " to come to the aid of their country\n"
+ " and pay their due taxes.";
byte buf[] = source.getBytes();
OutputStream f0 = new FileOutputStream("file1.txt");
for (int i=0; i < buf.length; i += 2) {
f0.write(buf[i]);
}
f0.close();
OutputStream f1 = new FileOutputStream("file2.txt");
f1.write(buf);
f1.close();
OutputStream f2 = new FileOutputStream("file3.txt");
f2.write(buf,buf.length-buf.length/4,buf.length/4);
f2.close();
}
}
Here are the contents of each file after running this program.
First, file1.txt:
Nwi h iefralgo e
t oet h i ftercuty n a hi u ae.
Next, file2.txt:
Now is the time for all good men
to come to the aid of their country
and pay their due taxes.
Finally, file3.txt:
nd pay their due taxes.
Reader
Reader is an abstract class that defines Java’s model of streaming character input. All of the
methods in this class will throw an IOException on error conditions. Table below provides a
synopsis of the methods in Reader.
FileReader
The FileReader class creates a Reader that you can use to read the contents of a file. Its two most
commonly used constructors are shown here:
FileReader(String filePath)
Prepared by: Navin K. Sharma 49 Java Unit 1
FileReader(File fileObj)
Either can throw a FileNotFoundException. Here, filePath is the full path name of a file, and
fileObj is a File object that describes the file.
The following example shows how to read lines from a file and print these to the standard output
stream. It reads its own source file, which must be in the current directory.
// Demonstrate FileReader.
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}
Writer
Writer is an abstract class that defines streaming character output. All of the methods in this class
return a void value and throw an IOException in the case of errors. Table below shows a
synopsis of the methods in Writer.
// Demonstrate FileWriter.
Prepared by: Navin K. Sharma 51 Java Unit 1
import java.io.*;
class FileWriterDemo {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good men\n"
+ " to come to the aid of their country\n"
+ " and pay their due taxes.";
char buffer[] = new char[source.length()];
source.getChars(0, source.length(), buffer, 0);
FileWriter f0 = new FileWriter("file1.txt");
for (int i=0; i < buffer.length; i += 2) {
f0.write(buffer[i]);
}
f0.close();
FileWriter f1 = new FileWriter("file2.txt");
f1.write(buffer);
f1.close();
FileWriter f2 = new FileWriter("file3.txt");
f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4);
f2.close();
}
}
A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an application.
A GUI (pronounced “GOO-ee”) gives an application a distinctive “look and feel.” GUIs are built from GUI
components. These are sometimes called controls or widgets—short for window gadgets. A GUI
component is an object with which the user interacts via the mouse, the keyboard or another form of
input, such as voice recognition. The Swing GUI components are defined in the javax.swing package.
Basic Controls
JList JMenu
JRadioButton JSlider
JTextField JPasswordField
Prepared by: Navin Kishor Sharma 1 Unit 2:User Interface using Swing
Interactive Controls
JColorChooser
JEditorPane
Prepared by: Navin Kishor Sharma 2 Unit 2:User Interface using Swing
JFileChooser
JTable
JTextArea JTree
Uneditable Controls
Prepared by: Navin Kishor Sharma 3 Unit 2:User Interface using Swing
Top-Level Containers
JDialog JFrame
JPanel JScrollPane
JTabbedPane JSplitPane
Prepared by: Navin Kishor Sharma 4 Unit 2:User Interface using Swing
Fig 3. Inheritance hierarchy for the Component class
There are actually two sets of Java GUI components. In Java’s early days, GUIs were built with
components from the Abstract Window Toolkit (AWT) in package java.awt. These look like the native
GUI components of the platform on which a Java program executes. For example, a Button object
displayed in a Java program running on Microsoft Windows looks like those in other Windows
Prepared by: Navin Kishor Sharma 5 Unit 2:User Interface using Swing
applications. On Apple Mac OS X, the Button looks like those in other Mac applications. Sometimes,
even the manner in which a user can interact with an AWT component differs between platforms. The
component’s appearance and the way in which the user interacts with it are known as its look-and-feel.
Swing GUI components allow you to specify a uniform look-and-feel for your application across all
platforms or to use each platform’s custom look-and-feel. An application can even change the look-and-
feel during execution to enable users to choose their own preferred look-and-feel.
Most Swing components are lightweight components—they’re written, manipulated and displayed
completely in Java. AWT components are heavyweight components, because they rely on the local
platform’s windowing system to determine their functionality and their look-and-feel. Several Swing
components are heavyweight components.
Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet. When
using these classes, you should keep these facts in mind:
1. To appear onscreen, every GUI component must be part of a containment hierarchy. A containment
hierarchy is a tree of components that has a top-level container as its root.
2. Each GUI component can be contained only once. If a component is already in a container and you try
to add it to another container, the component will be removed from the first container and then added
to the second.
3. Each top-level container has a content pane that, generally speaking, contains (directly or indirectly)
the visible components in that top-level container's GUI.
4. You can optionally add a menu bar to a top-level container. The menu bar is by convention positioned
within the top-level container, but outside the content pane.
Prepared by: Navin Kishor Sharma 6 Unit 2:User Interface using Swing
Each program that uses Swing components has at least one top-level container. This top-level container
is the root of a containment hierarchy — the hierarchy that contains all of the Swing components that
appear inside the top-level container.
As a rule, a standalone application with a Swing-based GUI has at least one containment hierarchy with
a JFrame as its root. For example, if an application has one main window and two dialogs, then the
application has three containment hierarchies, and thus three top-level containers. One containment
hierarchy has a JFrame as its root, and each of the other two has a JDialog object as its root.
A Swing-based applet has at least one containment hierarchy, exactly one of which is rooted by a
JApplet object. For example, an applet that brings up a dialog has two containment hierarchies. The
components in the browser window are in a containment hierarchy rooted by a JApplet object. The
dialog has a containment hierarchy rooted by a JDialog object.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(greenMenuBar);
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
/*
//Create a panel and add components to it.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(someBorder);
contentPane.add(someComponent, BorderLayout.CENTER);
contentPane.add(anotherComponent, BorderLayout.PAGE_END);
topLevelContainer.setContentPane(contentPane);
*/
Prepared by: Navin Kishor Sharma 7 Unit 2:User Interface using Swing
//Display the window.
frame.pack();
frame.setVisible(true);
}
Creating a Frame
A top-level window (that is, a window that is not contained inside another window) is called a frame in
Java. The AWT library has a class, called Frame, for this top level. The Swing version of this class is called
JFrame and extends the Frame class.
import javax.swing.*;
Prepared by: Navin Kishor Sharma 8 Unit 2:User Interface using Swing
{
public SimpleFrame()
{
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}
Swing GUI components are instances of class JFrame or a subclass of JFrame. JFrame is an indirect
subclass of class java.awt.Window that provides the basic attributes and behaviors of a window—a title
bar at the top, and buttons to minimize, maximize and close the window.
Buttons, text fields, and other user interface elements extend the class Component. Components can be
placed inside containers such as panels.
By default, closing a window simply hides the window. However, when the user closes the frame, we
would like the application to terminate. setDefaultCloseOperation method(inherited from class
JFrame) with constant JFrame.EXIT_ON_CLOSE as the argument indicate that the program should
terminate when the window is closed by the user.
Dialog boxes are windows in which programs display important messages to the user or obtain
informationfrom the user. Most applications you use on a daily basis use windows or dialog boxes (also
called dialogs) to interact with the user.
Java’s JOptionPane class (package javax.swing) provides prebuilt dialog boxes for both input and
output. These are displayed by invoking static JOptionPane methods. Program below presents a simple
addition application that uses two input dialogs to obtain integers from the user and a message dialog to
display the sum of the integers the user enters.
Prepared by: Navin Kishor Sharma 9 Unit 2:User Interface using Swing
{
public static void main( String[] args )
{
// obtain user input from JOptionPane input dialogs
String firstNumber =
JOptionPane.showInputDialog( "Enter first integer" );
String secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
// convert String inputs to int values for use in a calculation
int number1 = Integer.parseInt( firstNumber );
int number2 = Integer.parseInt( secondNumber );
int sum = number1 + number2; // add numbers
// display result in a JOptionPane message dialog
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );
} // end method main
} // end class Addition
Output
fig 1
Input Dialogs
Line 3 imports class JOptionPane. Lines 10–11 declare the local String variable first- Number and assign it
the result of the call to JOptionPane static method showInputDialog. This method displays an input
dialog using the method’s String argument ("Enter first integer") as a prompt.
Message Dailogs
Lines 22–23 use JOptionPane static method showMessageDialog to display a message dialog (the last
screen of Fig. 1) containing the sum. The first argument helps the Java application determine where to
Prepared by: Navin Kishor Sharma 10 Unit 2:User Interface using Swing
position the dialog box. A dialog is typically displayed from a GUI application with its own window. The
first argument refers to that window (known as the parent window) and causes the dialog to appear
centered over the parent. If the first argument is null, the dialog box is displayed at the center of your
screen. The second argument is the message to display—in this case, the result of concatenating the
String "The sum is " and the value of sum. The third argument—"Sum of Two Integers"—is the String
that should appear in the title bar at the top of the dialog. The fourth argument—
JOptionPane.PLAIN_MESSAGE—is the type ofmessage dialog to display. A PLAIN_MESSAGE dialog does
not display an icon to the left of the message.
The constants that represent the message dialog types are shown in Fig. 2. All message dialog types
except PLAIN_MESSAGE display an icon to the left of the message. These icons provide a visual
indication of the message’s importance to the user. A QUESTION_MESSAGE icon is the default icon for
an input dialog box (see Fig. 2).
fig. 2
JLabel
A typical GUI consists of many components. GUI designers often provide text stating the purpose of each
components. Such text is known as a label and is created with a JLabel—a subclass of JComponent. A
JLabel displays read-only text, an image, or both text and an image. Applications rarely change a label’s
contents after creating it.
// LabelFrame.java
// Demonstrating the JLabel class.
import java.awt.FlowLayout; // specifies how components are arranged
import javax.swing.JFrame; // provides basic window features
import javax.swing.JLabel; // displays text and images
import javax.swing.SwingConstants; // common constants used with Swing
import javax.swing.Icon; // interface used to manipulate images
import javax.swing.ImageIcon; // loads images
Prepared by: Navin Kishor Sharma 11 Unit 2:User Interface using Swing
public class LabelFrame extends JFrame
{
private JLabel label1; // JLabel with just text
private JLabel label2; // JLabel constructed with text and icon
private JLabel label3; // JLabel with added text and icon
// LabelTest.java
// Testing LabelFrame.
import javax.swing.JFrame;
Prepared by: Navin Kishor Sharma 12 Unit 2:User Interface using Swing
output
Normally, a user interacts with an application’s GUI to indicate the tasks that the application should
perform. For example, when you write an e-mail in an e-mail application, clicking the Send button tells
the application to send the e-mail to the specified e-mail addresses. GUIs are event driven. When the
user interacts with a GUI component, the interaction—known as an event—drives the program to
perform a task. Some common user interactions that cause an application to perform a task include
clicking a button, typing in a text field, selecting an item from a menu, closing a window and moving
the mouse. The code that performs a task in response to an event is called an event handler, and the
overall process of responding to events is known as event handling.
1. Create a class that represents the event handler and implements an appropriate interface—known as
an event-listener interface.
2. Indicate that an object of the class from Step 1 should be notified when the event occurs—known as
registering the event handler.
A text field is a basic text control that enables the user to type a small amount of text. When the user
indicates that text entry is complete (usually by pressing Enter), the text field fires an action event. If
you need to obtain more than one line of input from the user, use a text area.
Prepared by: Navin Kishor Sharma 13 Unit 2:User Interface using Swing
// Demonstrating the JTextField class.
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
Prepared by: Navin Kishor Sharma 14 Unit 2:User Interface using Swing
// construct passwordfield with default text
passwordField = new JPasswordField( "Hidden text" );
add( passwordField ); // add passwordField to JFrame
// Testing TextFieldFrame.
import javax.swing.JFrame;
Prepared by: Navin Kishor Sharma 15 Unit 2:User Interface using Swing
public class TextFieldTest
{
public static void main( String[] args )
{
TextFieldFrame textFieldFrame = new TextFieldFrame();
textFieldFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
textFieldFrame.setSize( 350, 100 ); // set frame size
textFieldFrame.setVisible( true ); // display frame
} // end main
} // end class TextFieldTest
output
Prepared by: Navin Kishor Sharma 16 Unit 2:User Interface using Swing
Many different types of events can occur when the user interacts with a GUI. The event information is
stored in an object of a class that extends AWTEvent (from package java.awt). Figure below illustrates a
hierarchy containing many event classes from the package java.awt.event. These event types are used
with both AWT and Swing components. Additional event types that are specific to Swing GUI
components are declared in package javax.swing.event.
Prepared by: Navin Kishor Sharma 17 Unit 2:User Interface using Swing
fig. Some event classes of package java.awt.event
The event-handling mechanism mainly consist of three parts—the event source, the event object and
the event listener. The event source is the GUI component with which the user interacts. The event
object encapsulates information about the event that occurred, such as a reference to the event source
and any event-specific information that may be required by the event listener for it to handle the event.
The event listener is an object that’s notified by the event source when an event occurs; in effect, it
“listens” for an event, and one of its methods executes in response to the event. A method of the event
listener receives an event object when the event listener is notified of the event. The event listener then
uses the event object to respond to the event. This event-handling model is known as the delegation
event model—an event’s processing is delegated to an object (the event listener) in the application.
For each event-object type, there’s typically a corresponding event-listener interface. An event listener
for a GUI event is an object of a class that implements one or more of the event-listener interfaces from
Prepared by: Navin Kishor Sharma 18 Unit 2:User Interface using Swing
packages java.awt.event and javax.swing.event. Many of the event-listener types are common to both
Swing and AWT components. Such types are declared in package java.awt.event, and some of them are
shown in Fig. below. Additional event-listener types that are specific to Swing components are declared
in package javax.swing.event.
Each event-listener interface specifies one or more event-handling methods that must be declared in
the class that implements the interface.Any class which implements an interface must declare all the
abstract methods of that interface; otherwise, the class is an abstract class and cannot be used to
create objects.
When an event occurs, the GUI component with which the user interacted notifies its registered
listeners by calling each listener’s appropriate event-handling method. For example, when the user
presses the Enter key in a JTextField, the registered listener’s actionPerformed method is called.
Prepared by: Navin Kishor Sharma 19 Unit 2:User Interface using Swing
fig. Some common event-listener interfaces of package java.awt.event
Prepared by: Navin Kishor Sharma 20 Unit 2:User Interface using Swing
Prepared by: Navin Kishor Sharma 21 Unit 2:User Interface using Swing
JCheckBox
Prepared by: Navin Kishor Sharma 22 Unit 2:User Interface using Swing
JButton
A button is a component the user clicks to trigger a specific action. A Java application can use several
types of buttons, including command buttons, checkboxes, toggle buttons and radio buttons. Figure
below shows the inheritance hierarchy of the Swing buttons . As you can see, all the button types are
subclasses of AbstractButton (package javax.swing), which declares the common features of Swing
buttons.
Prepared by: Navin Kishor Sharma 23 Unit 2:User Interface using Swing
fig. Swing button hierarchy.
A command button generates an ActionEvent when the user clicks it. Command buttons are created
with class JButton. The text on the face of a JButton is called a button label. A GUI can have many
JButtons, but each button label should be unique in the portion of the GUI that’s currently displayed.
The application below creates two JButtons and demonstrates that JButtons support the display of
Icons. Event handling for the buttons is performed by a single instance of inner class ButtonHandler.
// ButtonFrame.java
// Creating JButtons.
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
Prepared by: Navin Kishor Sharma 24 Unit 2:User Interface using Swing
Icon bug1 = new ImageIcon( getClass().getResource( "bug1.gif" ) );
Icon bug2 = new ImageIcon( getClass().getResource( "bug2.gif" ) );
fancyJButton = new JButton( "Fancy Button", bug1 ); // set image
fancyJButton.setRolloverIcon( bug2 ); // set rollover image
add( fancyJButton ); // add fancyJButton to JFrame
// ButtonTest.java
// Testing ButtonFrame.
import javax.swing.JFrame;
output
Prepared by: Navin Kishor Sharma 25 Unit 2:User Interface using Swing
JCheckBox
Classes JCheckBox and JRadioButton are subclasses of JToggleButton. A JRadioButton is different from a
JCheckBox in that normally several JRadioButtons are grouped together and are mutually exclusive—
only one in the group can be selected at any time where as more than one check box can be selected at
a time.
//CheckBoxFrame.java
// Creating JCheckBox buttons.
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
Prepared by: Navin Kishor Sharma 26 Unit 2:User Interface using Swing
{
super( "JCheckBox Test" );
setLayout( new FlowLayout() ); // set frame layout
// CheckBoxTest.java
// Testing CheckBoxFrame.
import javax.swing.JFrame;
Prepared by: Navin Kishor Sharma 27 Unit 2:User Interface using Swing
public static void main( String[] args )
{
CheckBoxFrame checkBoxFrame = new CheckBoxFrame();
checkBoxFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
checkBoxFrame.setSize( 275, 100 ); // set frame size
checkBoxFrame.setVisible( true ); // display frame
} // end main
} // end class CheckBoxTest
Output
JRadioButton
Radio buttons (declared with class JRadioButton) are similar to checkboxes in that they have two
states—selected and not selected (also called deselected). However, radio buttons normally appear as
a group in which only one button can be selected at a time .Selecting a different radio button forces all
others to be deselected. Radio buttons are used to represent mutually exclusive options (i.e., multiple
options in the group cannot be selected at the same time).
Prepared by: Navin Kishor Sharma 28 Unit 2:User Interface using Swing
private Font boldFont; // font for bold text
private Font italicFont; // font for italic text
private Font boldItalicFont; // font for bold and italic text
private JRadioButton plainJRadioButton; // selects plain text
private JRadioButton boldJRadioButton; // selects bold text
private JRadioButton italicJRadioButton; // selects italic text
private JRadioButton boldItalicJRadioButton; // bold and italic
private ButtonGroup radioGroup; // buttongroup to hold radio buttons
Prepared by: Navin Kishor Sharma 29 Unit 2:User Interface using Swing
italicJRadioButton.addItemListener(
new RadioButtonHandler( italicFont ) );
boldItalicJRadioButton.addItemListener(
new RadioButtonHandler( boldItalicFont ) );
} // end RadioButtonFrame constructor
//RadioButtonTest.java
// Testing RadioButtonFrame.
import javax.swing.JFrame;
output
Prepared by: Navin Kishor Sharma 30 Unit 2:User Interface using Swing
JComboBox (Using an Anonymous Inner Class for Event Handling)
A combo box (sometimes called a drop-down list) enables the user to select one item from a list .
Combo boxes are implemented with class JComboBox, which extends class JComponent. JComboBoxes
generate ItemEvents just as JCheckBoxes and JRadioButtons do. This example also demonstrates a
special form of inner class that’s used frequently in event handling.
Prepared by: Navin Kishor Sharma 31 Unit 2:User Interface using Swing
// handle JComboBox event
public void itemStateChanged( ItemEvent event )
{
// determine whether item selected
if ( event.getStateChange() == ItemEvent.SELECTED )
label.setIcon( icons[
imagesJComboBox.getSelectedIndex() ] );
} // end method itemStateChanged
} // end anonymous inner class
); // end call to addItemListener
add( imagesJComboBox ); // add combobox to JFrame
label = new JLabel( icons[ 0 ] ); // display first icon
add( label ); // add label to JFrame
} // end ComboBoxFrame constructor
}
Output
Prepared by: Navin Kishor Sharma 32 Unit 2:User Interface using Swing
JList
A list displays a series of items from which the user may select one or more items . Lists are created
with class JList, which directly extends class JComponent. Class JList supports single selection lists
(which allow only one item to be selected at a time) and multiple-selection lists(which allow any
number of items to be selected).
single-selection lists
The application below creates a JList containing 13 color names.When a color name is clicked in the JList,
a ListSelectionEvent occurs and the application changes the background color of the application window
to the selected color.
// ListFrame.java
// JList that displays a list of colors.
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.ListSelectionModel;
Prepared by: Navin Kishor Sharma 33 Unit 2:User Interface using Swing
Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK,
Color.RED, Color.WHITE, Color.YELLOW };
// ListFrame constructor add JScrollPane containing JList to JFrame
public ListFrame()
{
super( "List Test" );
setLayout( new FlowLayout() ); // set frame layout
colorJList = new JList( colorNames ); // create with colorNames
colorJList.setVisibleRowCount( 5 ); // display five rows at once
// do not allow multiple selections
colorJList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
// add a JScrollPane containing JList to frame
add( new JScrollPane( colorJList ) );
colorJList.addListSelectionListener(
new ListSelectionListener() // anonymous inner class
{
// handle list selection events
public void valueChanged( ListSelectionEvent event )
{
getContentPane().setBackground(
colors[colorJList.getSelectedIndex() ] );
} // end method valueChanged
} // end anonymous inner class
); // end call to addListSelectionListener
} // end ListFrame constructor
} // end class ListFrame
// ListTest.java
//Selecting colors from a JList.
import javax.swing.JFrame;
output
Prepared by: Navin Kishor Sharma 34 Unit 2:User Interface using Swing
Multiple-Selection Lists
A multiple-selection list enables the user to select many items from a JList.
// MultipleSelectionFrame.java
//Copying items from one List to another.
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
// MultipleSelectionFrame constructor
public MultipleSelectionFrame()
{
super( "Multiple Selection Lists" );
setLayout( new FlowLayout() ); // set frame layout
Prepared by: Navin Kishor Sharma 35 Unit 2:User Interface using Swing
// handle button event
public void actionPerformed( ActionEvent event )
{
// place selected values in copyJList
copyJList.setListData( colorJList.getSelectedValues() );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
//MultipleSelectionTest.java
//Testing MultipleSelectionFrame.
import javax.swing.JFrame;
output
Prepared by: Navin Kishor Sharma 36 Unit 2:User Interface using Swing
Mouse Event Handling
//MouseTrackerFrame.java
//Demonstrating mouse events.
import java.awt.Color;
import java.awt.BorderLayout;
Prepared by: Navin Kishor Sharma 37 Unit 2:User Interface using Swing
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
Prepared by: Navin Kishor Sharma 38 Unit 2:User Interface using Swing
statusBar.setText( String.format( "Released at [%d, %d]",
event.getX() event.getY() ));
} // end method mouseReleased
// MouseTrackerFrame.java
// Testing MouseTrackerFrame.
import javax.swing.JFrame;
Prepared by: Navin Kishor Sharma 39 Unit 2:User Interface using Swing
} // end class MouseTracker
output
Adapter Classes
Many event-listener interfaces, such as MouseListener and MouseMotionListener, contain multiple
methods. It’s not always desirable to declare every method in an event-listener interface. For instance,
an application may need only the mouseClicked handler from MouseListener or the mouseDragged
handler from MouseMotionListener. Interface WindowListener specifies seven window event-handling
methods. For many of the listener interfaces that have multiple methods, packages java.awt.event and
javax.swing.event provide event-listener adapter classes. An adapter class implements an interface and
provides a default implementation (with an empty method body) of each method in the interface.
Figure below shows several java.awt.event adapter classes and the interfaces they implement. You can
extend an adapter class to inherit the default implementation of every method and subsequently
override only the method(s) you need for event handling.
Prepared by: Navin Kishor Sharma 40 Unit 2:User Interface using Swing
fig. Event-adapter classes and the interfaces they implement in package java.awt.event.
//MouseDetailsFrame.java
// Demonstrating mouse clicks and distinguishing between mouse buttons.
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
Prepared by: Navin Kishor Sharma 41 Unit 2:User Interface using Swing
details = String.format( "Clicked %d time(s)",
event.getClickCount() );
if ( event.isMetaDown());
details += " with right mouse button";
else if( event.isAltDown())// middle mouse button
details += " with center mouse button";
else // left mouse button
details += " with left mouse button";
//MouseDetails.java
// Testing MouseDetailsFrame.
import javax.swing.JFrame;
public class MouseDetails
{
public static void main( String[] args )
{
MouseDetailsFrame mouseDetailsFrame = new MouseDetailsFrame();
mouseDetailsFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
mouseDetailsFrame.setSize( 400, 150 ); // set frame size
mouseDetailsFrame.setVisible( true ); // display frame
} // end main
} // end class MouseDetails
output
Prepared by: Navin Kishor Sharma 42 Unit 2:User Interface using Swing
Key Event Handling with JTextArea
Key events are generated when keys on the keyboard are pressed and released. A class that implements
KeyListener must provide declarations for methods keyPressed, keyReleased and key-Typed, each of
which receives a KeyEvent as its argument. Class KeyEvent is a subclass of InputEvent. Method
keyPressed is called in response to pressing any key. Method key- Typed is called in response to
pressing any key that is not an action key. (The action keys are any arrow key, Home, End, Page Up,
Page Down, any function key, etc.) Method key- Released is called when the key is released after any
keyPressed or keyTyped event.
The application below demonstrates the KeyListener methods. Class KeyDemoFrame implements the
KeyListener interface, so all three methods are declared in the application. The constructor registers
the application to handle its own key events by using method addKeyListener . Method addKey- Listener
is declared in class Component, so every subclass of Component can notify Key- Listener objects of key
events for that Component.
setDisabledTextColor to change the text color in the JTextArea to black for readability.
getKeyCode to get the virtual key code of the pressed key.Class KeyEvent contains virtual key-code
constants that represent every key on the keyboard.
getKey-Text the value returned by getKeyCode is passed to static KeyEvent method getKey- Text, which
returns a string containing the name of the key that was pressed.
get-KeyChar (which returns a char) to get the Unicode value of the character typed.
isActionKey to determine whether the key in the event was an action key.
getModifiers is called to determine whether any modifier keys (such as Shift, Alt and Ctrl) were
pressed when the key event occurred.
getKeyModifiersText which produces a string containing the names of the pressed modifier keys.
//KeyDemoFrame.java
//Demonstrating keystroke events.
import java.awt.Color;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextArea;
Prepared by: Navin Kishor Sharma 43 Unit 2:User Interface using Swing
public class KeyDemoFrame extends JFrame implements KeyListener
{
private String line1 = ""; // first line of textarea
private String line2 = ""; // second line of textarea
private String line3 = ""; // third line of textarea
private JTextArea textArea; // textarea to display output
// KeyDemoFrame constructor
public KeyDemoFrame()
{
super( "Demonstrating Keystroke Events" );
Prepared by: Navin Kishor Sharma 44 Unit 2:User Interface using Swing
line3 = String.format( "Modifier keys pressed: %s",
( temp.equals( "" ) ? "none" : temp ) ); // output modifiers
//KeyDemo.java
// Testing KeyDemoFrame.
import javax.swing.JFrame;
public class KeyDemo
{
public static void main( String[] args )
{
KeyDemoFrame keyDemoFrame = new KeyDemoFrame();
keyDemoFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
keyDemoFrame.setSize( 350, 100 ); // set frame size
keyDemoFrame.setVisible( true ); // display frame
} // end main
} // end class KeyDemo
output
Prepared by: Navin Kishor Sharma 45 Unit 2:User Interface using Swing
position and size. This functionality enables you to concentrate on the basic look-and-feel and lets the
layout managers process most of the layout details. All layout managers implement the interface
LayoutManager (in package java.awt). Class Container’s setLayout method takes an object that
implements the LayoutManager interface as an argument. There are basically three ways for you to
arrange components in a GUI:
1. Absolute positioning: This provides the greatest level of control over a GUI’s appearance. By setting a
Container’s layout to null, you can specify the absolute position of each GUI component with respect to
the upper-left corner of the Container by using Component methods setSize and setLocation or
setBounds. If you do this, you also must specify each GUI component’s size. Programming a GUI with
absolute positioning can be tedious, unless you have an integrated development environment (IDE) that
can generate the code for you.
2. Layout managers: Using layout managers to position elements can be simpler and faster than
creating a GUI with absolute positioning, but you lose some control over the size and the precise
positioning of GUI components.
3. Visual programming in an IDE: IDEs provide tools that make it easy to create GUIs. Each IDE typically
provides a GUI design tool that allows you to drag and drop GUI components from a tool box onto a
design area. You can then position, size and align GUI components as you like. The IDE generates the
Java code that creates the GUI. In addition, you can typically add event-handling code for a particular
component by double-clicking the component.
FlowLayout
FlowLayout is the simplest layout manager. GUI components are placed on a container from left to
right in the order in which they’re added to the container. When the edge of the container is reached,
components continue to display on the next line.
Class FlowLayout allows GUI components to be left aligned, centered (the default) and right aligned.
The application below creates three JButton objects and adds them to the application, using a
FlowLayout layout manager. The components are center aligned by default. When the user clicks Left,
the alignment for the layout manager is changed to a left-aligned FlowLayout. When the user clicks
Right, the alignment for the layout manager is changed to a right-aligned FlowLayout. When the user
clicks Center, the alignment for the layout manager is changed to a center-aligned FlowLayout.
//FlowLayoutFrame.java
//Demonstrating FlowLayout alignments.
Prepared by: Navin Kishor Sharma 46 Unit 2:User Interface using Swing
import java.awt.FlowLayout;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
Prepared by: Navin Kishor Sharma 47 Unit 2:User Interface using Swing
// realign attached components
layout.layoutContainer( container );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
// FlowLayoutDemo.java
// Testing FlowLayoutFrame.
import javax.swing.JFrame;
output
Prepared by: Navin Kishor Sharma 48 Unit 2:User Interface using Swing
BorderLayout
The BorderLayout layout manager (the default layout manager for a JFrame) arranges components
into five regions: NORTH, SOUTH, EAST, WEST and CENTER. NORTH corresponds to the top of the
container.
A BorderLayout limits a Container to containing at most five components—one in each region. The
components placed in the NORTH and SOUTH regions extend horizontally to the sides of the container
and are as tall as the components placed in those regions. The EAST and WEST regions expand vertically
between the NORTH and SOUTH regions and are as wide as the components placed in those regions.
The component placed in the CENTER region expands to fill all remaining space in the layout .
If all five regions are occupied, the entire container’s space is covered by GUI components. If the NORTH
or SOUTH region is not occupied, the GUI components in the EAST, CENTER and WEST regions expand
vertically to fill the remaining space. If the EAST or WEST region is not occupied, the GUI component in
the CENTER region expands horizontally to fill the remaining space. If the CENTER region is not occupied,
the area is left empty—the other GUI components do not expand
// BorderLayoutFrame.java
// Demonstrating BorderLayout.
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
Prepared by: Navin Kishor Sharma 49 Unit 2:User Interface using Swing
{
super( "BorderLayout Demo" );
layout = new BorderLayout( 5, 5 ); // 5 pixel gaps
setLayout( layout ); // set frame layout
buttons = new JButton[ names.length ]; // set size of array
// BorderLayoutDemo.java
// Testing BorderLayoutFrame.
import javax.swing.JFrame;
Prepared by: Navin Kishor Sharma 50 Unit 2:User Interface using Swing
output
GridLayout
The GridLayout layout manager divides the container into a grid so that components can be placed in
rows and columns. Class GridLayout inherits directly from class Object and implements interface
LayoutManager. Every Component in a GridLayout has the same width and height. Components are
added to a GridLayout starting at the top-left cell of the grid and proceeding left to right until the row is
full. Then the process continues left to right on the next row of the grid, and so on.
// GridLayoutFrame.java
// Demonstrating GridLayout.
import java.awt.GridLayout;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JButton;
Prepared by: Navin Kishor Sharma 51 Unit 2:User Interface using Swing
private JButton[] buttons; // array of buttons
private static final String[] names =
{ "one", "two", "three", "four", "five", "six" };
private boolean toggle = true; // toggle between two layouts
private Container container; // frame container
private GridLayout gridLayout1; // first gridlayout
private GridLayout gridLayout2; // second gridlayout
// no-argument constructor
public GridLayoutFrame()
{
super( "GridLayout Demo" );
gridLayout1 = new GridLayout( 2, 3, 5, 5 ); // 2 by 3; gaps of 5
gridLayout2 = new GridLayout( 3, 2 ); // 3 by 2; no gap
container = getContentPane(); // get content pane
setLayout( gridLayout1 ); // set JFrame layout
buttons = new JButton[ names.length ]; // create array of JButtons
// GridLayoutDemo.java
// Testing GridLayoutFrame.
import javax.swing.JFrame;
Prepared by: Navin Kishor Sharma 52 Unit 2:User Interface using Swing
gridLayoutFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
gridLayoutFrame.setSize( 300, 200 ); // set frame size
gridLayoutFrame.setVisible( true ); // display frame
} // end main
} // end class GridLayoutDemo
output
JSlider
JSliders enable a user to select from a range of integer values. Class JSlider inherits from JComponent.
Figure below shows a horizontal JSlider with tick marks and the thumb that
allows a user to select a value.
if a JSlider has the focus (i.e., it’s the currently selected GUI component in the user interface), the left
arrow key and right arrow key cause the thumb of the JSlider to decrease or increase by 1,
respectively. The down arrow key and up arrow key also cause the thumb to decrease or increase by 1
tick, respectively. The PgDn (page down) key and PgUp (page up) key cause the thumb to decrease or
increase by block increments of one-tenth of the range of values, respectively. The Home key moves
the thumb to the minimum value of the JSlider, and the End key moves the thumb to the maximum
value of the JSlider.
Prepared by: Navin Kishor Sharma 53 Unit 2:User Interface using Swing
The JSlider constructor takes four arguments. The first argument specifies the orientation of
Slider, which is HORIZONTAL or VERTICAL (a constant in interface SwingConstants). The second
and third arguments indicate the minimum and maximum integer values in the range of values
for this JSlider. The last argument indicates that the initial value of the JSlider (i.e., where the
thumb is displayed).
Method setMajorTickSpacing indicates that each major tick mark represents 10 values in the
range of values.
Method setPaintTicks with a true argument indicates that the tick marks should be displayed
(they aren’t displayed by default).
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Dimension;
import javax.swing.JPanel;
Prepared by: Navin Kishor Sharma 54 Unit 2:User Interface using Swing
} // end method setDiameter
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
// no-argument constructor
public SliderFrame()
{
super( "Slider Demo" );
Prepared by: Navin Kishor Sharma 55 Unit 2:User Interface using Swing
public void stateChanged( ChangeEvent e )
{
myPanel.setDiameter( diameterJSlider.getValue() );
} // end method stateChanged
} // end anonymous inner class
); // end call to addChangeListener
import javax.swing.JFrame;
Output
JColorChooser
Package javax.swing provides the JColorChooser GUI component that enables application users to select
colors. The application below demonstrates a JColorChooser dialog. When you click the Change Color
Prepared by: Navin Kishor Sharma 56 Unit 2:User Interface using Swing
button, a JColorChooser dialog appears. When you select a color and press the dialog’s OK button, the
background color of the application window changes.
//ShowColors2JFrame.java
//Choosing colors with JColorChooser.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JColorChooser;
import javax.swing.JPanel;
// set up GUI
public ShowColors2JFrame()
{
super( "Using JColorChooser" );
Prepared by: Navin Kishor Sharma 57 Unit 2:User Interface using Swing
add( colorJPanel, BorderLayout.CENTER ); // add colorJPanel
add( changeColorJButton, BorderLayout.SOUTH ); // add button
//ShowColors2.java
// Choosing colors with JColorChooser.
import javax.swing.JFrame;
output
Prepared by: Navin Kishor Sharma 58 Unit 2:User Interface using Swing
Class JMenuBar (a subclass of JComponent) contains the methods necessary to manage a
menu bar, which is a container for menus.
Class JMenu (a subclass of javax.swing.JMenu-Item) contains the methods necessary for managing
menus. Menus contain menu items and are added to menu bars or to other menus as submenus. When
a menu is clicked, it expands to show its list of menu items.
Class JMenuItem (a subclass of javax.swing.AbstractButton) contains the methods necessary to manage
menu items. A menu item is a GUI component inside a menu that, when selected, causes an action
event. A menu item can be used to initiate an action, or it can be a submenu that provides more menu
items from which the user can select. Submenus are useful for grouping related menu items in a menu.
Class JCheckBoxMenuItem (a subclass of javax.swing.JMenuItem) contains the methods necessary to
manage menu items that can be toggled on or off. When a JCheck-BoxMenuItem is selected, a check
appears to the left of the menu item. When the JCheck-BoxMenuItem is selected again, the check is
removed.
Class JRadioButtonMenuItem (a subclass of javax.swing.JMenuItem) contains the methods necessary to
manage menu items that can be toggled on or off like JCheckBox-MenuItems. When multiple
JRadioButtonMenuItems are maintained as part of a Button-Group, only one item in the group can be
selected at a given time. When a JRadioButtonMenuItem is selected, a filled circle appears to the left of
the menu item. When another JRadioButtonMenuItem is selected, the filled circle of the previously
selected menu item is removed.
// MenuFrame.java
// Demonstrating menus.
import java.awt.Color;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
Prepared by: Navin Kishor Sharma 59 Unit 2:User Interface using Swing
private JLabel displayJLabel; // displays sample text
private ButtonGroup fontButtonGroup; // manages font menu items
private ButtonGroup colorButtonGroup; // manages color menu items
private int style; // used to create style for font
Prepared by: Navin Kishor Sharma 60 Unit 2:User Interface using Swing
JMenu formatMenu = new JMenu( "Format" ); // create format menu
formatMenu.setMnemonic( 'r' ); // set mnemonic to r
Prepared by: Navin Kishor Sharma 61 Unit 2:User Interface using Swing
fonts[ 0 ].setSelected( true ); // select first Font menu item
fontMenu.addSeparator(); // add separator bar to font menu
Prepared by: Navin Kishor Sharma 62 Unit 2:User Interface using Swing
{
displayJLabel.setFont(
new Font( fonts[ count ].getText(), style, 72 ) );
} // end if
} // end for
displayJLabel.setFont( font );
repaint(); // redraw application
} // end method itemStateChanged
} // end class StyleHandler
} // end class MenuFrame
//MenuTest.java
//Testing MenuFrame.
import javax.swing.JFrame;
Prepared by: Navin Kishor Sharma 63 Unit 2:User Interface using Swing
} // end main
} // end class PopupTest
output
JPopupMenu
Many of today’s computer applications provide so-called context-sensitive pop-up menus. In Swing,
such menus are created with class JPopupMenu (a subclass of JComponent). These menus provide
options that are specific to the component for which the popup trigger event was generated. On most
systems, the pop-up trigger event occurs when the user presses and releases the right mouse button.
//PopupFrame.java
//Demonstrating JPopupMenus.
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.ButtonGroup;
Prepared by: Navin Kishor Sharma 64 Unit 2:User Interface using Swing
public PopupFrame()
{
super( "Using JPopupMenus" );
Prepared by: Navin Kishor Sharma 65 Unit 2:User Interface using Swing
} // end PopupFrame constructor
//PopupTest.java
// Testing PopupFrame.
import javax.swing.JFrame;
output
Prepared by: Navin Kishor Sharma 66 Unit 2:User Interface using Swing
JTabbedPane
A JTabbedPane arranges GUI components into layers, of which only one is visible at a time. Users access
each layer via a tab—similar to folders in a file cabinet. When the user clicks a tab, the appropriate layer
is displayed. The tabs appear at the top by default but also can be positioned at the left, right or bottom
of the JTabbedPane. Any component can be placed on a tab. If the component is a container, such as a
panel, it can use any layout manager to lay out several components on the tab. Class JTabbedPane is a
subclass of JComponent. The application below creates one tabbed pane with three tabs. Each tab
displays one of the JPanels—panel1, panel2 or panel3.
// JTabbedPaneFrame.java
// Demonstrating JTabbedPane
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.SwingConstants;
Prepared by: Navin Kishor Sharma 67 Unit 2:User Interface using Swing
panel3.add( new JButton( "West" ), BorderLayout.WEST );
panel3.add( new JButton( "East" ), BorderLayout.EAST );
panel3.add( new JButton( "South" ), BorderLayout.SOUTH );
panel3.add( label3, BorderLayout.CENTER );
tabbedPane.addTab( "Tab Three", null, panel3, "Third Panel" );
// JTabbedPaneDemo.java
// Demonstrating JTabbedPane.
import javax.swing.JFrame;
output
Tables
A table is a component that displays rows and columns of data. You can drag the cursor on column
boundaries to resize columns. You can also drag a column to a new position. Tables are implemented by
the JTable class, which extends JComponent.
Prepared by: Navin Kishor Sharma 68 Unit 2:User Interface using Swing
2. Create a JScrollPane object. (The arguments to the constructor specify the table and the policies for
vertical and horizontal scroll bars.)
3. Add the table to the scroll pane.
4. Add the scroll pane to JFrame
//TableFrame.java
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.BorderLayout;
import javax.swing.*;
//TableDemo.java
import javax.swing.JFrame;
Prepared by: Navin Kishor Sharma 69 Unit 2:User Interface using Swing
public class TableDemo
{
public static void main( String[] args )
{
TableFrame tableFrame = new TableFrame();
tableFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
tableFrame.setSize( 250, 200 ); // set frame size
tableFrame.setVisible( true ); // display frame
} // end main
} // end class Table
output
Trees
A tree is a component that presents a hierarchical view of data. A user has the ability to expand or
collapse individual subtrees in this display. Trees are implemented in Swing by the JTree class, which
extends JComponent.
A JTree object generates events when a node is expanded or collapsed. The addTreeExpansionListener(
) and removeTreeExpansionListener( ) methods allow listeners to register and unregister for these
notifications. The signatures of these methods are :
void addTreeExpansionListener(TreeExpansionListener tel)
void removeTreeExpansionListener(TreeExpansionListener tel)
The getPathForLocation( ) method is used to translate a mouse click on a specific point of the tree to a
tree path. Its signature is shown here:
TreePath getPathForLocation(int x, int y)
Here, x and y are the coordinates at which the mouse is clicked. The return value is a TreePath object
that encapsulates information about the tree node that was selected by the user.
The TreeNode interface declares methods that obtain information about a tree node. For example, it is
possible to obtain a reference to the parent node or an enumeration of the child nodes. The
MutableTreeNode interface extends TreeNode. It declares methods that can insert and remove child
nodes or change the parent node.
The DefaultMutableTreeNode class implements the MutableTreeNode interface. It represents a node
in a tree. One of its constructors is shown here:
Prepared by: Navin Kishor Sharma 70 Unit 2:User Interface using Swing
DefaultMutableTreeNode(Object obj)
Here, obj is the object to be enclosed in this tree node. The new tree node doesn’t have a parent or
children.
To create a hierarchy of tree nodes, the add( ) method of DefaultMutableTreeNode can be used. Its
signature is shown here:
void add(MutableTreeNode child)
Here, child is a mutable tree node that is to be added as a child to the current node.
Here are the steps that should be followed to use a tree in a JFrame:
1. Create a JTree object.
2. Create a JScrollPane object. (The arguments to the constructor specify the tree and the policies for
vertical and horizontal scroll bars.)
3. Add the tree to the scroll pane.
4. Add the scroll pane to the JFrame.
//TreeFrame.java
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
Prepared by: Navin Kishor Sharma 71 Unit 2:User Interface using Swing
// Create tree
tree = new JTree(top);
// Add tree to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane scrollPane = new JScrollPane(tree, v, h);
// Add scroll pane to Frame
add(scrollPane, BorderLayout.CENTER);
// Add text field to Frame
textField = new JTextField("", 20);
add(textField , BorderLayout.SOUTH);
// Anonymous inner class to handle mouse clicks
tree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
doMouseClicked(me);
}
});
}
void doMouseClicked(MouseEvent me) {
TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
if(tp != null)
textField.setText(tp.toString());
else
textField.setText("");
}
}
//TreeDemo.java
import javax.swing.JFrame;
output
Prepared by: Navin Kishor Sharma 72 Unit 2:User Interface using Swing
Creating GUI components in NetBeans using drag and drop
Step 1: Create a New Project
Step 2: Choose General -> Java Application
Step 3: Set a Project Name"CelsiusConverterProject".Make sure to deselect the "Create Main Class"
checkbox; leaving this option selected generates a new class as the main entry point for the application,
but our main GUI window (created in the next step) will serve that purpose, so checking this box is not
necessary. Click the "Finish" button when you are done.
Step 4: Add a JFrame Form-Now right-click the CelsiusConverterProject name and choose New ->
JFrame Form (JFrame is the Swing class responsible for the main frame for your application.)
Step 5: Name the GUI Class-Next type CelsiusConverterGUI as the class name, and CelsiusConverter as
the package name. The remainder of the fields should automatically be filled in, as shown above. Click
the Finish button when you are done.
When the IDE finishes loading, the right pane will display a design-time, graphical view of the
CelsiusConverterGUI. It is on this screen that you will visually drag, drop, and manipulate the various
Swing components.
NetBeans IDE Basics
It is not necessary to learn every feature of the NetBeans IDE before exploring its GUI creation
capabilities. In fact, the only features that you really need to understand are the Palette, the Design
Area, the Property Editor, and the Inspector.
The Palette
The Palette contains all of the components offered by the Swing API(JLabel is a text label, JList is a drop-
down list, etc.).
The Design Area
The Design Area is where you will visually construct your GUI. It has two views: source view, and design
view. Design view is the default, as shown below. You can toggle between views at any time by clicking
their respective tabs.
The Property Editor
The Property Editor does what its name implies: it allows you to edit the properties of each component.
The Property Editor is intuitive to use; in it you will see a series of rows — one row per property — that
you can click and edit without entering the source code directly.
The Inspector
The Inspector provides a graphical representation of your application's components. We will use the
Inspector only once, to change a few variable names to something other than their defaults.
Creating the CelsiusConverter GUI
Prepared by: Navin Kishor Sharma 73 Unit 2:User Interface using Swing
This section explains how to use the NetBeans IDE to create the application's GUI. As you drag each
component from the Palette to the Design Area, the IDE auto-generates the appropriate source code.
Step 1: Set the Title
First, set the title of the application's JFrame to "Celsius Converter", by single-clicking the JFrame in the
Inspector:Then, set its title with the Property Editor:
Prepared by: Navin Kishor Sharma 74 Unit 2:User Interface using Swing
Step 3: Add a JLabel
Step 4: Add a JButton
Step 5: Add a Second JLabel
Prepared by: Navin Kishor Sharma 75 Unit 2:User Interface using Swing
Step 1: Set the Component Text
First, double-click the JTextField and JButton to change the default text that was inserted by the IDE.
When you erase the text from the JTextField, it will shrink in size as shown below. Change the text of the
JButton from "JButton1" to "Convert." Also change the top JLabel text to "Celsius" and the bottom to
"Fahrenheit."
Step 2: Set the Component Size
Next, shift-click the JTextField and JButton components. This will highlight each showing that they are
selected. Right-click (control-click for mac users) Same Size -> Same Width. The components will now be
the same width, as shown below. When you perform this step, make sure that JFrame itself is not also
selected. If it is, the Same Size menu will not be active.
Step 3: Remove Extra Space
Finally, grab the lower right-hand corner of the JFrame and adjust its size to eliminate any extra
whitespace. Note that if you eliminate all of the extra space (as shown below) the title (which only
appears at runtime) may not show completely. The end-user is free to resize the application as desired,
but you may want to leave some extra space on the right side to make sure that everything fits correctly.
Experiment, and use the screenshot of the finished GUI as a guide.
Prepared by: Navin Kishor Sharma 76 Unit 2:User Interface using Swing
The default names are not very relevant in the context of this application, so it makes sense to change
them from their defaults to something that is more meaningful. Right-click each variable name and
choose "Change variable name." When you are finished, the variable names should appear as follows:
Prepared by: Navin Kishor Sharma 77 Unit 2:User Interface using Swing
In the Design Area, click on the Convert button to select it. Make sure that only the Convert button is
selected (if the JFrame itself is also selected, this step will not work.) Right-click the Convert button and
choose Events -> Action -> ActionPerformed. This will generate the required event-handling code,
leaving you with empty method bodies in which to add your own functionality:
Prepared by: Navin Kishor Sharma 78 Unit 2:User Interface using Swing
Step 3: Add the Temperature Conversion Code
The final step is to simply paste the temperature conversion code into the empty method body.
//Parse degrees Celsius as a double and convert to Fahrenheit.
int tempFahr = (int)((Double.parseDouble(tempTextField.getText()))
* 1.8 + 32);
fahrenheitLabel.setText(tempFahr + " Fahrenheit");
Simply copy this code and paste it into the convertButtonActionPerformed method as shown below:
Prepared by: Navin Kishor Sharma 79 Unit 2:User Interface using Swing
Unit 3- Database Connectivity
A database is an organized collection of data. There are many different strategies for organizing data to
facilitate easy access and manipulation. A database management system(DBMS) provides mechanisms
for storing, organizing, retrieving and modifying data form any users. Database management systems
allow for the access and storage of data without concern for the internal representation of data.
Today’s most popular database systems are relational databases.A language called SQL—pronounced
“sequel,” or as its individual letters—is the international standard language used almost universally with
relational databases to perform queries (i.e., to request information that satisfies given criteria) and to
manipulate data.
Some popular relational database management systems (RDBMSs) are Microsoft SQL Server, Oracle,
Sybase, IBM DB2, Informix, PostgreSQL and MySQL. The JDK now comes with a pure-Java RDBMS called
Java DB—Oracles’s version of Apache Derby.
Java programs communicate with databases and manipulate their data using the Java Database
Connectivity (JDBC™) API. A JDBC driver enables Java applications to connect to a database in a
particular DBMS and allows you to manipulate that database using the JDBC API.
JDBC Introduction
The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational
Database.
JDBC helps to write Java applications that manage these three programming activities:
Retrieve and process the results received from the database in answer to your query
JDBC Driver Manager — The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC
architecture. It is quite small and simple.
JDBC Test Suite — The JDBC driver test suite helps you to determine that JDBC drivers will run your
program. These tests are not comprehensive or exhaustive, but they do exercise many of the important
features in the JDBC API.
JDBC-ODBC Bridge — The Java Software bridge provides JDBC access via ODBC drivers. Note that you
need to load ODBC binary code onto each client machine that uses this driver. As a result, the ODBC
driver is most appropriate on a corporate network where client installations are not a major problem, or
for application server code written in Java in a three-tier architecture.
A type 2 driver is written partly in Java and partly in native code; it communicates with the
client API of a database. When you use such a driver, you must install some platform-specific
code in addition to a Java library.
A type 3 driver is a pure Java client library that uses a database-independent protocol to
communicate database requests to a server component, which then translates the requests into
a database-specific protocol. This can simplify deployment since the database-dependent code
is located only on the server.
A type 4 driver is a pure Java library that translates JDBC requests directly to a database-specific
protocol.
Most database vendors supply either a type 3 or type 4 driver with their database. Furthermore, a
number of third-party companies specialize in producing drivers with better standards conformance,
support for more platforms, better performance, or, in some cases, simply better reliability than the
drivers that are provided by the database vendors.
Communication between the client and middle tier can occur through HTTP (when you use a web
browser as the client), RMI (when you use an application), or another mechanism. JDBC manages the
communication between the middle tier and the back-end database. Figure below shows the basic three
tier architecture.
Extract the zip file to a folder, you’ll see file ‘mysql-connector-java-5.1.20-bin.jar’ which is the library file
that we want. Just copy the file to the library folder, for example to “C:\Program Files\Java\jdk1.7\lib”
also to the “C:\Program Files\Java\jdk1.7\jre\lib directory.
In the services tab of the netbeans , right click the database and click on 'new connection'. Under the
'new connection wizard', click on the 'Driver Combobox' and select the 'mySQL Connector/J driver' and
click on 'next' untill the wizard completes.
// DisplayAuthors.java
// Displaying the contents of the Authors table.
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
while(resultSet.next())
{
for ( int i = 1; i <= numberOfColumns; i++ )
System.out.printf( "%-8s\t",resultSet.getObject( i ));
System.out.println();
} // end while
} // end try
catch(SQLException sqlException)
{
sqlException.printStackTrace();
} // end catch
finally // ensure resultSet, statement and connection are closed
{
try
{
resultSet.close();
statement.close();
connection.close();
} // end try
catch ( Exception exception )
{
exception.printStackTrace();
} // end catch
} // end finally
} // end main
} // end class DisplayAuthors
output
ResultSet Interface
The ResultSet interface provides methods for retrieving and manipulating the results of executed
queries, and ResultSet objects can have different functionality and characteristics. These characteristics
are type, concurrency, and cursor holdability.
ResultSet Types
The type of a ResultSet object determines the level of its functionality in two areas: the ways in which
the cursor can be manipulated, and how concurrent changes made to the underlying data source are
reflected by the ResultSet object.
The sensitivity of a ResultSet object is determined by one of three different ResultSet types:
(a)TYPE_FORWARD_ONLY: The result set cannot be scrolled; its cursor moves forward only, from before
the first row to after the last row. The rows contained in the result set depend on how the underlying
database generates the results. That is, it contains the rows that satisfy the query at either the time the
query is executed or as the rows are retrieved.
(b)TYPE_SCROLL_INSENSITIVE: The result can be scrolled; its cursor can move both forward and
backward relative to the current position, and it can move to an absolute position. The result set is
insensitive to changes made to the underlying data source while it is open. It contains the rows that
satisfy the query at either the time the query is executed or as the rows are retrieved.
(c)TYPE_SCROLL_SENSITIVE: The result can be scrolled; its cursor can move both forward and backward
relative to the current position, and it can move to an absolute position. The result set reflects changes
made to the underlying data source while the result set remains open.
Note: Not all databases and JDBC drivers support all ResultSet types. The method
DatabaseMetaData.supportsResultSetType returns true if the specified ResultSet type is supported and
false otherwise.
ResultSet Concurrency
The concurrency of a ResultSet object determines what level of update functionality is supported.
There are two concurrency levels:
CONCUR_READ_ONLY: The ResultSet object cannot be updated using the ResultSet interface.
CONCUR_UPDATABLE: The ResultSet object can be updated using the ResultSet interface.
The following ResultSet constants may be supplied to the Connection methods createStatement,
prepareStatement, and prepareCall:
HOLD_CURSORS_OVER_COMMIT: ResultSet cursors are not closed; they are holdable: they are held
open when the method commit is called. Holdable cursors might be ideal if your application uses mostly
read-only ResultSet objects.
CLOSE_CURSORS_AT_COMMIT: ResultSet objects (cursors) are closed when the commit method is
called. Closing cursors when this method is called can result in better performance for some
applications.
// query database
resultSet = statement.executeQuery(
"SELECT AuthorID, FirstName, LastName FROM authors" );
while ( resultSet.next() )
{
int id = rs.getInt("AuthorID");
String firstName = rs.getString("FirstName");
String lastName = rs.getString("LastName");
System.out.println(id+ "\t" + firstName+
"\t" + lastName );
} // end while
} // end try
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
Cursors
As mentioned previously, you access the data in a ResultSet object through a cursor, which points to
one row in the ResultSet object. However, when a ResultSet object is first created, the cursor is
positioned before the first row.There are other methods available to move the cursor:
next: Moves the cursor forward one row. Returns true if the cursor is now positioned on a row and false
if the cursor is positioned after the last row.
previous: Moves the cursor backward one row. Returns true if the cursor is now positioned on a row
and false if the cursor is positioned before the first row.
first: Moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now
positioned on the first row and false if the ResultSet object does not contain any rows.
last: Moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now
positioned on the last row and false if the ResultSet object does not contain any rows.
beforeFirst: Positions the cursor at the start of the ResultSet object, before the first row. If the ResultSet
object does not contain any rows, this method has no effect.
afterLast: Positions the cursor at the end of the ResultSet object, after the last row. If the ResultSet
object does not contain any rows, this method has no effect.
relative(int rows): Moves the cursor relative to its current position.
absolute(int row): Positions the cursor on the row specified by the parameter row.
Note that the default sensitivity of a ResultSet is TYPE_FORWARD_ONLY, which means that it cannot be
scrolled; you cannot call any of these methods that move the cursor, except next, if your ResultSet
cannot be scrolled.
try {
// establish connection to database
connection = DriverManager.getConnection(
DATABASE_URL, "root", "" );
statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs= statement.executeQuery(
"SELECT * FROM authors");
while (uprs.next()) {
uprs.updateString( "LastName","Sharma");
uprs.updateRow();
}
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
The field ResultSet.TYPE_SCROLL_SENSITIVE creates a ResultSet object whose cursor can move both
forward and backward relative to the current position and to an absolute position. The field
ResultSet.CONCUR_UPDATABLE creates a ResultSet object that can be updated. See the ResultSet
Javadoc for other fields you can specify to modify the behavior of ResultSet objects.
The method ResultSet.updateString updates the specified column (in this example, LastName with the
specified float value in the row where the cursor is positioned. ResultSet contains various updater
methods that enable you to update column values of various data types. However, none of these
updater methods modifies the database; you must call the method ResultSet.updateRow to update the
database.
try {
statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
uprs.moveToInsertRow();
uprs.updateInt("AuthorID",9);
uprs.updateString("FirstName","Subash");
uprs.updateString("LastName","Pakhrin");
uprs.insertRow();
uprs.beforeFirst();
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
The same stipulations for using strings in getter methods also apply to updater methods.
The method ResultSet.moveToInsertRow moves the cursor to the insert row. The insert row is a special
row associated with an updatable result set. It is essentially a buffer where a new row can be
constructed by calling the updater methods prior to inserting the row into the result set. For example,
this method calls the method ResultSet.updateString to update the insert row's COF_NAME column to
Kona.
The method ResultSet.insertRow inserts the contents of the insert row into the ResultSet object and into
the database.
Note: After inserting a row with the ResultSet.insertRow, you should move the cursor to a row other
than the insert row. For example, this example moves it to before the first row in the result set with the
method ResultSet.beforeFirst. Unexpected results can occur if another part of your application uses the
same result set and the cursor is still pointing to the insert row.
The list, which is associated with a Statement object at its creation, is initially empty. You can add SQL
commands to this list with the method addBatch and empty it with the method clearBatch. When you
have finished adding statements to the list, call the method executeBatch to send them all to the
database to be executed as a unit, or batch.
try {
connection = DriverManager.getConnection(
DATABASE_URL, "root", "" );
connection.setAutoCommit(false);
statement = connection.createStatement();
statement.addBatch(
"INSERT INTO authors " +
"VALUES('15','Hari','Shrestha')");
statement.addBatch(
"INSERT INTO authors " +
"VALUES('16','Ram','Acharya')");
statement.addBatch(
"INSERT INTO authors " +
"VALUES('17','Shyam','Gautam')");
statement.addBatch(
"INSERT INTO authors " +
"VALUES('18','Govinda','Paudel')");
} catch(BatchUpdateException b) {
b.printStackTrace();
} catch(SQLException ex) {
ex.printStackTrace();
}
The following line disables auto-commit mode for the Connection object con so that the transaction will
not be automatically committed or rolled back when the method executeBatch is called.
connection.setAutoCommit(false);
To allow for correct error handling, you should always disable auto-commit mode before beginning a
batch update.
The method Statement.addBatch adds a command to the list of commands associated with the
Statement object statement. In this example, these commands are all INSERT INTO statements, each
one adding a row consisting of three column values.
The following line sends the four SQL commands that were added to its list of commands to the
database to be executed as a batch:
Note that statement uses the method executeBatch to send the batch of insertions, not the method
executeUpdate, which sends only one command and returns a single update count. The DBMS
executes the commands in the order in which they were added to the list of commands, so it will first
add the row of values for "Hari" , then add the row for "Ram", then "Shyam" , and finally "Govinda". If all
four commands execute successfully, the DBMS will return an update count for each command in the
order in which it was executed. The update counts that indicate how many rows were affected by each
command are stored in the array updateCounts.
If all four of the commands in the batch are executed successfully, updateCounts will contain four
values, all of which are 1 because an insertion affects one row. The list of commands associated with
stmt will now be empty because the four commands added previously were sent to the database when
stmt called the method executeBatch. You can at any time explicitly empty this list of commands with
the method clearBatch.
The Connection.commit method makes the batch of updates to the "authors" table permanent. This
method needs to be called explicitly because the auto-commit mode for this connection was disabled
previously.
The following line enables auto-commit mode for the current Connection object.
connection.setAutoCommit(true);
Now each statement in the example will automatically be committed after it is executed, and it no
longer needs to invoke the method commit.
PreparedStatements
A PreparedStatement enables you to create compiled SQL statements that execute more efficiently
than Statements. PreparedStatements can also specify parameters, making them more flexible than
Statements—you can execute the same query repeatedly with different
parameter values.
The PreparedStatement is derived from the more general class, Statement. If you want to execute a
Statement object many times, it usually reduces execution time to use a PreparedStatement object
instead.
Performing Parameterized Batch Update using PreparedStatement
It is also possible to have a parameterized batch update, as shown in the following code fragment,
where con is a Connection object:
try {
connection = DriverManager.getConnection(
DATABASE_URL, "root", "" );
connection.setAutoCommit(false);
PreparedStatement pstmt = connection.prepareStatement(
"INSERT INTO authors VALUES(?, ?, ?)");
pstmt.setInt(1,19);
pstmt.setString(2, "Navin");
pstmt.setString(3,"Sharma");
pstmt.addBatch();
pstmt.setInt(1,20);
pstmt.setString(2, "Rajesh");
pstmt.setString(3,"Paudel");
pstmt.addBatch();
The three question marks (?) in the the preceding SQL statement’s last line are placeholders for values
that will be passed as part of the query to the database. Before executing a PreparedStatement, the
program must specify the parameter values by using the Prepared- Statement interface’s set methods.
For the preceding query, parameters are int and strings that can be set with Prepared- Statement
method setInt and setString.
Method setInt's and setString’s first argument represents the parameter number being set, and the
second argument is that parameter’s value. Parameter numbers are counted from 1, starting with the
first question mark (?).
Interface PreparedStatement provides set methods for each supported SQL type. It’s important to use
the set method that is appropriate for the parameter’s SQL type in the database—SQLExceptions
occur when a program attempts to convert a parameter value to an incorrect type.
Transaction Processing
Many database applications require guarantees that a series of database insertions, updates and
deletions executes properly before the application continues processing the next database operation.
For example, when you transfer money electronically between bank accounts, several factors determine
if the transaction is successful. You begin by specifying the source account and the amount you wish to
transfer from that account to a destination account. Next, you specify the destination account. The bank
checks the source account to determine whether its funds are sufficient to complete the transfer. If so,
the bank withdraws the specified amount and, if all goes well, deposits it into the destination account to
complete the transfer. What happens if the transfer fails after the bank withdraws the money from the
source account? In a proper banking system, the bank redeposits the money in the source account.The
way to be sure that either both actions occur or neither action occurs is to use a transaction. A
transaction is a set of one or more statements that is executed as a unit, so either all of the
statements are executed, or none of the statements is executed.
The way to allow two or more statements to be grouped into a transaction is to disable the auto-
commit mode.
Disabling Auto-Commit Mode
When a connection is created, it is in auto-commit mode. This means that each individual SQL statement
is treated as a transaction and is automatically committed right after it is executed.
The way to allow two or more statements to be grouped into a transaction is to disable the auto-
commit mode.
con.setAutoCommit(false);
Committing Transactions
After the auto-commit mode is disabled, no SQL statements are committed until you call the method
commit explicitly. All statements executed after the previous call to the method commit are included in
the current transaction and committed together as a unit.
con.commit();
Rollback
If you group update statements to a transaction, then the transaction either succeeds in its entirety and
it can be committed, or it fails somewhere in the middle. In that case, you can carry out a rollback and
the database automatically undoes the effect of all updates that occurred since the last committed
transaction.
Save Points
You can gain finer-grained control over the rollback process by using save points. Creating a save point
marks a point to which you can later return without having to return to the start of the transaction. For
example,
Here, we used an anonymous save point. You can also give the save point a name, such as
Savepoint svpt = conn.setSavepoint("stage1");
When you are done with a save point, you should release it:
stat.releaseSavepoint(svpt);
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.BatchUpdateException;
import java.sql.PreparedStatement;
try {
// establish connection to database
connection = DriverManager.getConnection(
DATABASE_URL, "root", "" );
statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs= statement.executeQuery(
"SELECT * FROM authors");
while (uprs.next()) {
uprs.updateString( "LastName","Sharma");
uprs.updateRow();
}
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
try {
statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
uprs.moveToInsertRow();
uprs.updateInt("AuthorID",9);
uprs.updateString("FirstName","Subash");
uprs.updateString("LastName","Pakhrin");
uprs.insertRow();
uprs.beforeFirst();
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
try {
connection.setAutoCommit(false);
statement = connection.createStatement();
statement.addBatch(
"INSERT INTO authors " +
"VALUES('15','Hari','Shrestha')");
statement.addBatch(
"INSERT INTO authors " +
"VALUES('16','Ram','Acharya')");
statement.addBatch(
"INSERT INTO authors " +
"VALUES('17','Shyam','Gautam')");
statement.addBatch(
"INSERT INTO authors " +
"VALUES('18','Govinda','Paudel')");
} catch(BatchUpdateException b) {
b.printStackTrace();
} catch(SQLException ex) {
ex.printStackTrace();
}
try {
connection.setAutoCommit(false);
PreparedStatement pstmt = connection.prepareStatement(
"INSERT INTO authors VALUES(?, ?, ?)");
pstmt.setInt(1,19);
pstmt.setString(2, "Navin");
pstmt.setString(3,"Sharma");
pstmt.addBatch();
pstmt.setInt(1,20);
pstmt.setString(2, "Rajesh");
pstmt.setString(3,"Paudel");
pstmt.addBatch();
// query database
resultSet = statement.executeQuery(
"SELECT AuthorID, FirstName, LastName FROM authors" );
while ( resultSet.next() )
{
for ( int i = 1; i <= numberOfColumns; i++ )
System.out.printf( "%-8s\t", resultSet.getObject( i ) );
System.out.println();
} // end while
} // end try
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
} // end try
catch ( Exception exception )
{
exception.printStackTrace();
} // end catch
} // end finally
} // end main
} // end class DisplayAuthors
RowSet Interface
A JDBC RowSet object holds tabular data in a way that makes it more flexible and easier to use than a
result set.The RowSet interface configures the database connection and prepares query statements
automatically.It provides several set methods that allow you to specify the properties needed to
establish a connection (such as the database URL, user name and password of the database) and create
a Statement (such as a query). RowSet also provides several get methods that return these properties.
Connected and Disconnected RowSets
There are two types of RowSet objects—connected and disconnected. A connected RowSet object
connects to the database once and remains connected while the object is in use. A disconnected
RowSet object connects to the database, executes a query to retrieve the data from the database and
then closes the connection. A program may change the data in a disconnected RowSet while it’s
disconnected. Modified data can be updated in the database
after a disconnected RowSet reestablishes the connection with the database.
JdbcRowSet
Navigating JdbcRowSet Objects
JdbcRowSet jdbcRs = new JdbcRowSetImpl();
jdbcRs.absolute(4);
jdbcRs.previous();
Inserting Rows
jdbcRs.moveToInsertRow();
jdbcRs.updateInt("Author_ID", 10);
jdbcRs.updateString("FirstName", "Navin");
jdbcRs.updateString("LastName", "Sharma");
jdbcRs.insertRow();
Deleting Rows
jdbcRs.last();
jdbcRs.deleteRow();
CachedRowSet
Creating CachedRowSet Objects:
achedRowSet crs = new CachedRowSetImpl();
Setting up command:
crs.setCommand("select * from Authors");
When you write Java programs that communicate over the network, you are programming at the
application layer. Typically, you don't need to concern yourself with the TCP and UDP layers. Instead,
you can use the classes in the java.net package. These classes provide system-independent network
communication. However, to decide which Java classes your programs should use, you do need to
understand how TCP and UDP differ.
Transmission Control Protocol (TCP)
TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data
between two computers.
When two applications want to communicate to each other reliably, they establish a connection and
send data back and forth over that connection. This is analogous to making a telephone call. If you want
to speak to your friend, a connection is established when you dial his phone number and he answers.
You send data back and forth over the connection by speaking to one another over the phone lines. Like
the phone company, TCP guarantees that data sent from one end of the connection actually gets to
the other end and in the same order it was sent. Otherwise, an error is reported.
TCP provides a point-to-point channel for applications that require reliable communications. The
Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of
applications that require a reliable communication channel. The order in which the data is sent and
received over the network is critical to the success of these applications. When HTTP is used to read
from a URL, the data must be received in the order in which it was sent. Otherwise, user end up with a
jumbled HTML file, a corrupt zip file, or some other invalid information.
User Datagram Protocol (UDP)
UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams,
from one computer to another with no guarantees about arrival.
The UDP protocol provides for communication that is not guaranteed between two applications on the
network. UDP is not connection-based like TCP. Rather, it sends independent packets of data, called
datagrams, from one application to another. Sending datagrams is much like sending a letter through
the postal service: The order of delivery is not important and is not guaranteed, and each message is
For many applications, the guarantee of reliability is critical to the success of the transfer of information
from one end of the connection to the other. However, other forms of communication don't require
such strict standards. In fact, they may be slowed down by the extra overhead or the reliable
connection may invalidate the service altogether.
Consider, for example, a clock server that sends the current time to its client when requested to do so. If
the client misses a packet, it doesn't really make sense to resend it because the time will be incorrect
when the client receives it on the second try. If the client makes two requests and receives packets from
the server out of order, it doesn't really matter because the client can figure out that the packets are out
of order and make another request. The reliability of TCP is unnecessary in this instance because it
causes performance degradation and may hinder the usefulness of the service.
Another example of a service that doesn't need the guarantee of a reliable channel is the ping
command. The purpose of the ping command is to test the communication between two programs over
the network. In fact, ping needs to know about dropped or out-of-order packets to determine how good
or bad the connection is. A reliable channel would invalidate this service altogether.
Many firewalls and routers have been configured not to allow UDP packets. If you're having trouble
connecting to a service outside your firewall, or if clients are having trouble connecting to your service,
you should check whether UDP is permitted.
Ports
The TCP and UDP protocols use ports to map incoming data to a particular process running on a
computer.Generally speaking, a computer has a single physical connection to the network. All data
destined for a particular computer arrives through that connection. However, the data may be intended
for different applications running on the computer. So how does the computer know to which
application to forward the data? Through the use of ports.
Data transmitted over the Internet is accompanied by addressing information that identifies the
computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which
IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number,
which TCP and UDP use to deliver the data to the right application.
In connection-based communication such as TCP, a server application binds a socket to a specific port
number. This has the effect of registering the server with the system to receive all data destined for that
port. A client can then rendezvous with the server at the server's port.
In datagram-based communication such as UDP, the datagram packet contains the port number of its
destination and UDP routes the packet to the appropriate application.
Java programs that interact with the Internet also may use URLs to find the resources on the Internet
they wish to access. Java programs can use a class called URL in the java.net package to represent a
URL address.
The term URL can be ambiguous. It can refer to an Internet address or a URL object in a Java program.
Here "URL address" is used to mean an Internet address and "URL object" to refer to an instance of the
URL class in a program.
URL
URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the
Internet.If you've been surfing the Web, you have undoubtedly heard the term URL and have used URLs
to access HTML pages from the Web.
It's often easiest, although not entirely accurate, to think of a URL as the name of a file on the World
Wide Web because most URLs refer to a file on some machine on the network. However, remember
that URLs also can point to other resources on the network, such as database queries and command
output.
A URL has two main components:
Protocol identifier: For the URL http://example.com, the protocol identifier is http.
Note that the protocol identifier and the resource name are separated by a colon and two forward
slashes. The protocol identifier indicates the name of the protocol to be used to fetch the resource. The
example uses the Hypertext Transfer Protocol (HTTP), which is typically used to serve up hypertext
documents. HTTP is just one of many different protocols used to access different types of resources on
the net. Other protocols include File Transfer Protocol (FTP), Gopher, File, and News.
The resource name is the complete address to the resource. The format of the resource name depends
entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one
or more of the following components:
Host Name
The name of the machine on which the resource lives.
Filename
The pathname to the file on the machine.
Port Number
The port number to which to connect (typically optional).
Reference
A reference to a named anchor within a resource that usually identifies a specific location within a file
(typically optional).
For many protocols, the host name and the filename are required, while the port number and reference
are optional. For example, the resource name for an HTTP URL must specify a server on the network
(Host Name) and the path to the document on that machine (Filename); it also can specify a port
number and a reference.
Creating a URL
The easiest way to create a URL object is from a String that represents the human-readable form of the
URL address. This is typically the form that another person will use for a URL. In your Java program, you
can use a String containing this text to create a URL object:
The URL object created above represents an absolute URL. An absolute URL contains all of the
information necessary to reach the resource in question. You can also create URL objects from a relative
URL address.
The first argument is a URL object that specifies the base of the new URL. The second argument is a
String that specifies the rest of the resource name relative to the base. If baseURL is null, then this
constructor treats relativeURL like an absolute URL specification. Conversely, if relativeURL is an
absolute URL specification, then the constructor ignores baseURL.
The first argument is the protocol, the second is the host name, and the last is the pathname of the file.
Note that the filename contains a forward slash at the beginning. This indicates that the filename is
specified from the root of the host.
The final URL constructor adds the port number to the list of arguments used in the previous
constructor:
URL url = new URL("http", "example.com", 80, "pages/page1.html");
This creates a URL object for the following URL:
http://example.com:80/pages/page1.html
If you construct a URL object using one of these constructors, you can get a String containing the
complete URL address by using the URL object's toString method or the equivalent toExternalForm
method.
MalformedURLException
Each of the four URL constructors throws a MalformedURLException if the arguments to the constructor
refer to a null or unknown protocol. Typically, you want to catch and handle this exception by
embedding your URL constructor statements in a try/catch pair, like this:
try {
URL myURL = new URL(...);
}
Parsing a URL
The URL class provides several methods that let you query URL objects. You can get the protocol,
authority, host name, port number, path, query, filename, and reference from a URL using these
accessor methods:
getProtocol
Returns the protocol identifier component of the URL.
getAuthority
Returns the authority component of the URL.
getHost
Returns the host name component of the URL.
getPort
Returns the port number component of the URL. The getPort method returns an integer that is the
port number. If the port is not set, getPort returns -1.
getPath
Returns the path component of this URL.
getQuery
Returns the query component of this URL.
getFile
Returns the filename component of the URL. The getFile method returns the same as getPath, plus
the concatenation of the value of getQuery, if any.
getRef
Returns the reference component of the URL.
Note:
Remember that not all URL addresses contain these components. The URL class provides these methods
because HTTP URLs do contain these components and are perhaps the most commonly used URLs. The
URL class is somewhat HTTP-centric.
You can use these getXXX methods to get information about the URL regardless of the constructor that
you used to create the URL object.
The URL class, along with these accessor methods, frees you from ever having to parse URLs again!
Given any string specification of a URL, just create a new URL object and call any of the accessor
methods for the information you need. This small example program creates a URL from a string
specification and then uses the URL object's accessor methods to parse the URL:
import java.net.*;
import java.io.*;
protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING
The following small Java program uses openStream() to get an input stream on the URL
http://www.google.com.np/. It then opens a BufferedReader on the input stream and reads from the
BufferedReader thereby reading from the URL. Everything read is copied to the standard output stream:
import java.net.*;
import java.io.*;
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
When you run the program, you should see, scrolling by in your command window, the HTML
commands and textual content from the HTML file located at http://www.google.com.np/.
Connecting to a URL
After you've successfully created a URL object, you can call the URL object's openConnection method to
get a URLConnection object, or one of its protocol specific subclasses, e.g. java.net.HttpURLConnection
You can use this URLConnection object to setup parameters and general request properties that you
may need before connecting. Connection to the remote object represented by the URL is only initiated
when the URLConnection.connect method is called. When you do this you are initializing a
communication link between your Java program and the URL over the network. For example, the
following code opens a connection to the site example.com:
try {
URL myURL = new URL("http://example.com/");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
catch (IOException e) {
// openConnection() failed
// ...
}
A new URLConnection object is created every time by calling the openConnection method of the
protocol handler for this URL.
You are not always required to explicitly call the connect method to initiate the connection. Operations
that depend on being connected, like getInputStream, getOutputStream, etc, will implicitly perform the
connection, if necessary.
Now that you've successfully connected to your URL, you can use the URLConnection object to perform
actions such as reading from or writing to the connection. The next example shows how.
The output from this program is identical to the output from the program that opens a stream directly
from the URL. You can use either way to read from a URL. However, reading from a URLConnection
instead of reading directly from a URL might be more useful. This is because you can use the
URLConnection object for other tasks (like writing to the URL) at the same time.
Sockets
URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the
Internet. Sometimes your programs require lower-level network communication, for example, when you
want to write a client-server application.
In client-server applications, the server provides some service, such as processing database queries or
sending out current stock prices. The client uses the service provided by the server, either displaying
database query results to the user or making stock purchase recommendations to an investor. The
communication that occurs between the client and the server must be reliable. That is, no data can be
dropped and it must arrive on the client side in the same order in which the server sent it.
TCP provides a reliable, point-to-point communication channel that client-server applications on the
Internet use to communicate with each other. To communicate over TCP, a client program and a server
program establish a connection to one another. Each program binds a socket to its end of the
connection. To communicate, the client and the server each reads from and writes to the socket bound
to the connection.
What Is a Socket?
Normally, a server runs on a specific computer and has a socket that is bound to a specific port number.
The server just waits, listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running and
the port number on which the server is listening. To make a connection request, the client tries to
rendezvous with the server on the server's machine and port. The client also needs to identify itself to
the server so it binds to a local port number that it will use during this connection. This is usually
assigned by the system.
On the client side, if the connection is accepted, a socket is successfully created and the client can use
the socket to communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.
Definition:
A socket is one endpoint of a two-way communication link between two programs running on the
network. A socket is bound to a port number so that the TCP layer can identify the application that data
is destined to be sent.
An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely
identified by its two endpoints. That way you can have multiple connections between your host and the
server.
The java.net package in the Java platform provides a class, Socket, that implements one side of a two-
way connection between your Java program and another program on the network. The Socket class sits
on top of a platform-dependent implementation, hiding the details of any particular system from your
Java program. By using the java.net.Socket class instead of relying on native code, your Java programs
can communicate over the network in a platform-independent fashion.
Additionally, java.net includes the ServerSocket class, which implements a socket that servers can use
to listen for and accept connections to clients.
If you are trying to connect to the Web, the URL class and related classes (URLConnection, URLEncoder)
are probably more appropriate than the socket classes. In fact, URLs are a relatively high-level
connection to the Web and use sockets as part of the underlying implementation.
InetAddress class
Usually, you don't have to worry too much about Internet addresses, the numerical host addresses that
consist of four bytes (or, with IPv6, 16 bytes) such as 132.163.4.102. However, you can use the
InetAddress class if you need to convert between host names and Internet addresses.
As of JDK 1.4, the java.net package supports IPv6 Internet addresses, provided the host operating
system does.
The static getByName method returns an InetAddress object of a host. For example,
InetAddress address = InetAddress.getByName("HostName");
returns an InetAddress object that encapsulates the sequence of four bytes such as 132.163.4.104.
Some host names with a lot of traffic correspond to multiple Internet addresses, to facilitate load
balancing. For example,the host name java.sun.com corresponds to three different Internet addresses.
One of them is picked at random when the host is accessed. You can get all hosts with the
getAllByName method.
InetAddress[] addresses = InetAddress.getAllByName(host);
String getHostAddress()-returns a string with decimal numbers, separated by periods, for example,
"132.163.4.102".
String getHostName()-returns the host name.
//Client.java
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String a[])throws IOException
{
try
Every time we know the program has established a new socket connection, that is, when the call to
accept was successful, we will launch a new thread to take care of the connection between the server
and that client. The main program will just go back and wait for the next connection. For this to happen,
the main loop of the server should look like this:
while (true)
{
Socket incoming = s.accept();
Runnable r = new ThreadedEchoHandler(incoming);
The THReadedEchoHandler class implements Runnable and contains the communication loop with the
client in its run method.
Socket Timeouts
In real-life programs, you don't just want to read from a socket, because the read methods will block
until data are available. If the host is unreachable, then your application waits for a long time and you
are at the mercy of the underlying operating system to time out eventually. Instead, you should decide
what timeout value is reasonable for your particular application. Then, call the setSoTimeout method to
set a timeout value (in milliseconds).
Socket s = new Socket(. . .);
s.setSoTimeout(10000); // time out after 10 seconds
If the timeout value has been set for a socket, then all subsequent read and write operations throw a
SocketTimeoutException when the timeout has been reached before the operation has completed its
work. You can catch that exception and react to the timeout.
try
{
Scanner in = new Scanner(s.getInputStream());
String line = in.nextLine();
Interruptible Sockets
When you connect to a socket, the current thread blocks until the connection has been established or a
timeout has elapsed. Similarly, when you read or write data through a socket, the current thread blocks
until the operation is successful or has timed out.
In interactive applications, you would like to give users an option to simply cancel a socket connection
that does not appear to produce results. However, if a thread blocks on an unresponsive socket, you
cannot unblock it by calling interrupt.
To interrupt a socket operation, you use a SocketChannel, a feature of the java.nio package. Open the
SocketChannel like this:
SocketChannel channel = SocketChannel.open(new InetSocketAddress(host, port));
A channel does not have associated streams. Instead, it has read and write methods that make use of
Buffer objects.These methods are declared in interfaces ReadableByteChannel and
WritableByteChannel.
If you don't want to deal with buffers, you can use the Scanner class to read from a SocketChannel
because Scanner has a constructor with a ReadableByteChannel parameter:
Scanner in = new Scanner(channel);
To turn a channel into an output stream, use the static Channels.newOutputStream method.
OutputStream outStream = Channels.newOutputStream(channel);
That's all you need to do. Whenever a thread is interrupted during an open, read, or write operation,
the operation does not block but is terminated with an exception.
Half-Close
When a client program sends a request to the server, the server needs to be able to determine when
the end of the request occurs. For that reason, many Internet protocols (such as SMTP) are line
oriented. Other protocols contain a header that specifies the size of the request data. Otherwise,
indicating the end of the request data is harder than writing data to a file. With a file, you'd just close
the file at the end of the data. However, if you close a socket, then you immediately disconnect from the
server.
The half-close overcomes this problem. You can close the output stream of a socket, thereby indicating
to the server the end of the request data, but keep the input stream open so that you can read the
response.
The server side simply reads input until the end of the input stream is reached.This protocol is only
useful for one-shot services such as HTTP where the client connects, issues a request, catches the
response, and then disconnects.
//SendMail.java
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
try {
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Beans are important, because they allow you to build complex systems from software components.
These components may be provided by you or supplied by one or more different vendors. Java Beans
defines an architecture that specifies how these building blocks can operate together. To better
understand the value of Beans, consider the following. Hardware designers
have a wide variety of components that can be integrated together to construct a system. Resistors,
capacitors, and inductors are examples of simple building blocks. Integrated circuits provide more
advanced functionality. All of these different parts can be reused. It is not necessary or possible to
rebuild these capabilities each time a new system is needed. Also, the same pieces can be used in
different types of circuits. This is possible because the behavior of these components is understood and
documented.
Unfortunately, the software industry has not been as successful in achieving the benefits of reusability
and interoperability. Large applications grow in complexity and become very difficult to maintain and
enhance. Part of the problem is that, until recently, there has not been a standard, portable way to write
a software component. To achieve the benefits of component software, a component architecture is
needed that allows programs to be assembled from software building blocks, perhaps provided by
different vendors. It must also be possible for a designer to select a component, understand its
capabilities, and incorporate it into an application. When a new version of a component becomes
available, it should be easy to incorporate this functionality into existing code.Fortunately, Java Beans
provides just such an architecture.
A software component architecture provides standard mechanisms to deal with software building
blocks. The following list enumerates some of the specific benefits that Java technology provides for a
component developer:
Bean obtains all the benefits of Java’s “write-once, run-anywhere” paradigm.
The properties, events, and methods of a Bean that are exposed to an application builder tool
can be controlled.
A Bean may be designed to operate correctly in different locales, which makes it useful in global
markets.
Auxiliary software can be provided to help a person configure a Bean. This software is only
needed when the design-time parameters for that component are being set. It does not need to
be included in the run-time environment.
The configuration settings of a Bean can be saved in persistent storage and restored at a later
time.
A Bean may register to receive events from other objects and can generate events that are sent
to other objects.
Steps for creating a new Bean using netbeans
Here are the steps that you must follow to create a new Bean:
7. Test.
Explanation
1. Create a Directory for the New Bean (You can use netbeans and create a new project for that)
//Colors.java
import java.awt.*;
import java.awt.event.*;
1. Start NetBeans. Choose File > New Project... from the menu.
2. Select Java from the Categories list and select Java Application from the Projects list. Click Next
3. Enter SnapApp as the application name. Uncheck Create Main Class and click Finish. NetBeans creates
the new project and you can see it in NetBeans' Projects pane:
4. Right-click on the SnapApp project and choose New > JFrame Form... from the popup menu.
5. Fill in SnapFrame for the class name and snapapp as the package. Click Finish. NetBeans creates the
new class and shows its visual designer:
In the Projects pane on the left, you can see the newly created SnapFrame class. In the center of the
screen is the NetBeans visual designer. On the right side is the Palette, which contains all the
components you can add to the frame in the visual designer.
6. Take a closer look at the Palette. All of the components listed are beans. The components are grouped
by function. Scroll to find the Swing Controls group, then click on Button and drag it over into the visual
designer. The button is a bean!
Under the palette on the right side of NetBeans is an inspector pane that you can use to examine and
manipulate the button. Try closing the output window at the bottom to give the inspector pane more
space.
Properties
The properties of a bean are the things you can change that affect its appearance or internal state. For
the button in this example, the properties include the foreground color, the font, and the text that
appears on the button. The properties are shown in two groups. Properties lists the most frequently
used properties, while Other Properties shows less commonly used properties.
Go ahead and edit the button's properties. For some properties, you can type values directly into the
table. For others, click on the ... button to edit the value. For example, click on ... to the right of the
foreground property. A color chooser dialog pops up and you can choose a new color for the foreground
text on the button. Try some other properties to see what happens. Notice you are not writing any code.
Events
Beans can also fire events. Click on the Events button in the bean properties pane. You'll see a list of
every event that the button is capable of firing.
You can use NetBeans to hook up beans using their events and properties. To see how this works, drag a
Label out of the palette into the visual designer for SnapFrame.
To wire the button and the label together, click on the Connection Mode button in the visual designer
toolbar.
Click on the button in the SnapFrame form. NetBeans outlines the button in red to show that it is the
component that will be generating an event.
Click on the label. NetBeans' Connection Wizard pops up. First you will choose the event you wish to
respond to. For the button, this is the action event. Click on the + next to action and select
actionPerformed. Click Next >.
Now you get to choose what happens when the button fires its action event. The Connection Wizard
lists all the properites in the label bean. Select text in the list and click Next.
In the final screen of the Connection Wizard, fill in the value you wish to set for the text property. Click
on Value, then type You pressed the button! or something just as eloquent. Click Finish.
NetBeans wires the components together and shows you its handiwork in the source code editor.
Click on the Design button in the source code toolbar to return to the UI designer. Click Run Main
Project or press F6 to build and run your project.
NetBeans builds and runs the project. It asks you to identify the main class, which is SnapFrame. When
the application window pops up, click on the button. You'll see your immortal prose in the label.
Notice that you did not write any code. This is the real power of JavaBeans — with a good builder tool
like NetBeans, you can quickly wire together components to create a running application.
Almost any code can be packaged as a bean. The beans you have seen so far are all visual beans, but
beans can provide functionality without having a visible component.
The power of JavaBeans is that you can use software components without having to write them or
understand their implementation.
This page describes how you can add a JavaBean to your application and take advantage of its
functionality.
Download an example JavaBean component, BumperSticker. Beans are distributed as JAR files. Save the
file somewhere on your computer. BumperSticker is graphic component and exposes one method, go(),
that kicks off an animation.
To add BumperSticker to the NetBeans palette, choose Tools > Palette > Swing/AWT Components from
the NetBeans menu.
Click on the Add from JAR... button. NetBeans asks you to locate the JAR file that contains the beans you
wish to add to the palette. Locate the file you just downloaded and click Next.
NetBeans shows a list of the classes in the JAR file. Choose the ones you wish you add to the palette. In
this case, select BumperSticker and click Next
Finally, NetBeans needs to know which section of the palette will receive the new beans. Choose Beans
and click Finish.
Click Close to make the Palette Manager window go away. Now take a look in the palette.
BumperSticker is there in the Beans section.
Go ahead and drag BumperSticker out of the palette and into your form.
You can work with the BumperSticker instance just as you would work with any other bean. To see this
in action, drag another button out into the form. This button will kick off the BumperSticker's animation.
Wire the button to the BumperSticker bean, just as you already wired the first button to the text field.
Click on the + next to action and select actionPerformed. Click Next >.
Select Method Call, then select go() from the list. Click Finish.
Run the application again. When you click on the second button, the BumperSticker component
animates the color of the heart.
Again, notice how you have produced a functioning application without writing any code.
Unit 7. Servlets and Java Server Pages
Servlets
Servlets are small programs that execute on the server side of a Web connection. Just as applets
dynamically extend the functionality of a Web browser, servlets dynamically extend the functionality of
a Web server.
A servlet is a Java programming language class used to extend the capabilities of servers that host
applications accessed via a request-response programming model. Although servlets can respond to any
type of request, they are commonly used to extend the applications hosted by Web servers. For such
applications, Java Servlet technology defines HTTP-specific servlet classes.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.
The following table summarizes the core classes that are provided in the javax.servlet package.
Class Description
GenericServlet Implements the Servlet and ServletConfig interfaces.
ServletInputStream Provides an input stream for reading requests from a client.
ServletOutputStream Provides an output stream for writing responses to a client.
ServletException Indicates a servlet error occurred.
UnavailableException Indicates a servlet is unavailable.
Note: For detailed information about javax.servlet package refer to the following link
http://docs.oracle.com/javaee/1.4/api/javax/servlet/package-summary.html
//index.jsp
<html>
<body>
<center>
//PostParametersServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
output
e = navin
p = 9841
//TestingGet
import java.io.PrintWriter;
import java.io.IOException;
import java.sql.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
connection=DriverManager.getConnection( "jdbc:mysql://localhost:3306/testingget","root","");
uprs.moveToInsertRow();
uprs.updateString("firstname",firstName);
uprs.updateString("lastname",surname);
uprs.insertRow();
uprs.beforeFirst();
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
}
try
{
// query database
ResultSet resultSet = statement.executeQuery(
"SELECT * from names" );
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("<p>Welcome " + firstName + " " + surname + "</p>");
out.println( "<p>People currently in the database:</p>" );
// process query results
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for ( int i = 1; i <= numberOfColumns; i++ )
}//end try
finally {
out.close();
}
}
// close SQL statements and database when servlet terminates
public void destroy()
{
// attempt to close statements and database connection
try
{
statement.close();
connection.close();
} // end try
// handle database exceptions by returning error to client
catch( SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
} // end method destroy
}
Handling HTTP POST Requests
Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked when a form
on a Web page is submitted.
//index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Testing POST</title>
//TestingPost
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Using Cookies
Now, let’s develop a servlet that illustrates how to use cookies. The servlet is invoked when a form on a
Web page is submitted. The example contains three files as summarized here:
File Description
index.jsp Allows a user to specify a value for the cookie
named MyCookie.
AddCookie.java Processes the submission of AddCookie.htm.
GetCookie.java Displays cookie values.
//AddCookie.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// Create cookie.
Cookie cookie = new Cookie("FirstCookie", data);
Cookie cookie1 = new Cookie("SecondCookie", data1);
//GetCookie.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Session Tracking
HTTP is a stateless protocol. Each request is independent of the previous one. However, in some
applications, it is necessary to save state information so that information can be collected from several
interactions between a browser and a server. Sessions provide such a mechanism.
A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object is
returned. This object can store a set of bindings that associate names with objects. The setAttribute( ),
getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these
bindings. It is important to note that session state is shared among all the servlets that are associated
with a particular client.
//index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Testing Cookies</title>
</head>
<body>
<label style="color: blue"><b>Testing Session</b></label></br>
<label><b>Click below to get Session Value</b></label></br>
<a href="getSession">click here</a>
</body>
</html>
//GetSession.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet GetSession</title>");
out.println("</head>");
out.println("<body>");
if(date != null) {
out.print("Last access: " + date + "<br>");
}
date = new Date();
hs.setAttribute("date", date);
out.println("Current date: " + date);
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
JavaServer Pages simplify the delivery of dynamic Web content. They enable Web application
programmers to create dynamic content by reusing predefined components and by interacting with
components using server-side scripting. Custom-tag libraries are a powerful feature of JSP that allows
Java developers to hide complex code for database access and other useful services for dynamic Web
pages in custom tags. Web sites use these custom tags like any other Web page element to take
advantage of the more complex functionality hidden by the tag. Thus, Web-page designers who are not
familiar with Java can enhance Web pages with powerful dynamic content and processing capabilities.
The classes and interfaces that are specific to JavaServer Pages programming are located in packages
In some ways, JavaServer Pages look like standard XHTML or XML documents. In fact, JSPs normally
include XHTML or XML markup. Such markup is known as fixed-template data or fixed-template text.
Fixed-template data often helps a programmer decide whether to use a servlet or a JSP. Programmers
tend to use JSPs when most of the content sent to the client is fixed-template data and little or none of
the content is generated dynamically with Java code. Programmers typically use servlets when only a
small portion of the content sent to the client is fixed-template data. In fact, some servlets do not
produce content. Rather, they perform a task on behalf of the client, then invoke other servlets or JSPs
to provide a response. Note that in most cases servlet and JSP technologies are interchangeable. As with
servlets, JSPs normally execute as part of a Web server.
When a JSP-enabled server receives the first request for a JSP, the JSP container translates the JSP into a
Java servlet that handles the current request and future requests to the JSP. Literal text in a JSP
becomes string literals in the servlet that represents the translated JSP. Any errors that occur in
compiling the new servlet result in translation-time errors. The JSP container places the Java statements
that implement the JSP's response in method _jspService at translation time. If the new servlet compiles
properly, the JSP container invokes method _jspService to process the request. The JSP may respond
directly or may invoke other Web application components to assist in processing the request. Any errors
that occur during request processing are known as request-time errors.
Overall, the request-response mechanism and the JSP life cycle are the same as those of a servlet. JSPs
can override methods jspInit and jspDestroy (similar to servlet methods init and destroy), which the JSP
container invokes when initializing and terminating a JSP, respectively. JSP programmers can define
these methods using JSP declarations--part of the JSP scripting mechanism.
output
As you can see, most of test.jsp consists of XHTML markup.In cases like this, JSPs are easier to
implement than servlets. In a servlet that performs the same task as this JSP, each line of XHTML
markup typically is a separate Java statement that outputs the string representing the markup as part of
the response to the client. Writing code to output markup can often lead to errors.That's whhy in such
scenarios JSP is preferred than Servlets.The key line in the above program is the expression
JSP expressions are delimited by <%= and %>. The preceding expression creates a new instance of class
Date (package java.util). By default, a Date object is initialized with the current date and time. When the
client requests this JSP, the preceding expression inserts the String representation of the date and time
We use the XHTML meta element in line 9 to set a refresh interval of 60 seconds for the document. This
causes the browser to request test.jsp every 60 seconds. For each request to test.jsp, the JSP container
reevaluates the expression in line 24, creating a new Date object with the server's current date and
time.
When you first invoke the JSP, you may notice a brief delay as GlassFish Server translates the JSP into a
servlet and invokes the servlet to respond to your request
Implicit Objects
Implicit objects provide access to many servlet capabilities in the context of a JavaServer Page. Implicit
objects have four scopes: application, page, request and session. The JSP container owns objects with
application scope. Any JSP can manipulate such objects. Objects with page scope exist only in the page
that defines them. Each page has its own instances of the page-scope implicit objects. Objects with
request scope exist for the duration of the request. For example, a JSP can partially process a request,
then forward it to a servlet or another JSP for further processing. Request-scope objects go out of scope
when request processing completes with a response to the client. Objects with session scope exist for
the client's entire browsing session. Figure below describes the JSP implicit objects and their scopes.
Scripting
JavaServer Pages often present dynamically generated content as part of an XHTML document that is
Scripting Components
The JSP scripting components include scriptlets, comments, expressions, declarations and escape
sequences.
Scriptlets are blocks of code delimited by <% and %>. They contain Java statements that the container
places in method _jspService at translation time.
JSPs support three comment styles: JSP comments, XHTML comments and scripting-language
comments. JSP comments are delimited by <%-- and --%>. These can be placed throughout a JSP, but
not inside scriptlets. XHTML comments are delimited with <!-- and -->. These, too, can be placed
throughout a JSP, but not inside scriptlets. Scripting language comments are currently Java comments,
because Java currently is the only JSP scripting language. Scriptlets can use Java's end-of-line //
comments and traditional comments (delimited by /* and */). JSP comments and scripting-language
comments are ignored and do not appear in the response to a client. When clients view the source code
of a JSP response, they will see only the XHTML comments in the source code. The different comment
styles are useful for separating comments that the user should be able to see from those that document
logic processed on the server.
JSP expressions are delimited by <%= and %> and contain a Java expression that is evaluated when a
client requests the JSP containing the expression. The container converts the result of a JSP expression
to a String object, then outputs the String as part of the response to the client.
Declarations, delimited by <%! and %>, enable a JSP programmer to define variables and methods for
use in a JSP. Variables become instance variables of the servlet class that represents the translated JSP.
Similarly, methods become members of the class that represents the translated JSP. Declarations of
variables and methods in a JSP use Java syntax. Thus, a variable declaration must end with a semicolon,
as in
Special characters or character sequences that the JSP container normally uses to delimit JSP code can
be included in a JSP as literal characters in scripting elements, fixed template data and attribute values
using escape sequences. Figure below shows the literal character or characters and the corresponding
escape sequences and discusses where to use the escape sequences.
Scripting Example
//welcome.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Processing "get" requests with data</title>
</head>
<!-- body section of document -->
<body>
<% // begin scriptlet
String name = request.getParameter( "firstName" );
if ( name != null )
{
%> <%-- end scriptlet to insert fixed template data --%>
<h1>
Hello <%= name %>, <br />
Welcome to JavaServer Pages!
</h1>
} // end if
else {
} // end else
Output
Standard Actions
Standard actions provide JSP implementors with access to several of the most common tasks performed
in a JSP, such as including content from other resources, forwarding requests to other resources and
interacting with JavaBean software components. JSP containers process actions at request time.
Actions are delimited by <jsp:action> and </jsp:action>, where action is the standard action name. In
cases where nothing appears between the starting and ending tags, the XML empty element syntax <jsp:
action /> can be used. Figure below summarizes the JSP standard actions.
//index.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LN TECH PVT. LTD</title>
table, tr, td
{
font-size: .9em;
border: 3px groove;
padding: 5px;
background-color: yellowgreen;
}
</style>
</head>
<body>
<table style="width: 1280px; height: 675px">
<tr>
<td style = "width: 215px; text-align: center">
<img src = "LN_Tech_logo.jpg"
width = "140" height = "93"
alt = "LN Tech Logo" />
</td>
<td>
<%-- include banner.html in this JSP --%>
<jsp:include page = "banner.html"
//banner.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div style = "width: 580px">
<p><b>
LN Tech....a dedicated team of Engineers <br /> Working
in the field of Web<br />
welcomes you to explore our site</b>
</p>
<p>
<a href = "mailto:admin@lntech.com">admin@lntech.com</a>
<br />Baneshwor<br />Kathmandu, Nepal
</p>
</div>
</body>
</html>
//toc.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
//clock.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Clock Page</title>
</head>
<body>
<table>
<tr>
<td style = "background-color: blanchedalmond;">
<p class = "big" style = "color: black; font-size: 3em;
font-weight: bold;">
//signup.jsp
<!DOCTYPE html>
<html>
<!-- head section of document -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sign up Page</title>
</head>
<!-- body section of document -->
<body>
<% // begin scriptlet
if ( name != null )
{
%> <%-- end scriptlet to insert fixed template data --%>
<h1>
Hello <%= name %>, <br />
Welcome to LN Tech!
</h1>
} // end if
else {
} // end else
output
The Remote Method Invocation (RMI) model represents a distributed object application. RMI allows an
object inside a JVM (a client) to invoke a method on an object running on a remote JVM (a server) and
have the results returned to the client.
Therefore, RMI implies a client and a server.
The server application typically creates an object and makes it accessible remotely.
Therefore, the object is referred to as a remote object.
The server registers the object that is available to clients.
One of the ways this can be accomplished is through a naming facility provided as part of the JDK, which
is called the rmiregistry. The server uses the registry to bind an arbitrary name to a
remote object. A client application receives a reference to the object on the server and then invokes
methods on it. The client looks up the name in the registry and obtains a reference to an object that is
able to interface with the remote object. The reference is referred to as a remote object reference.
Most importantly, a method invocation on a remote object has the same syntax as a method invocation
on a local object.
RMI Architecture
The interface that the client and server objects use to interact with each other is provided through
stubs/skeleton, remote reference, and transport layers. Stubs and skeletons are Java objects that act as
proxies to the client and server, respectively.
All the network-related code is placed in the stub and skeleton, so that the client and server will not
have to deal with the network and sockets in their code. The remote reference layer handles the
creation of and management of remote objects. The transport layer is the protocol that sends remote
object requests across the network.
A simple diagram showing the above relationships is shown below.
Client Server
Stub Skeleton
Network Connection
//RemoteInterface.java
import java.rmi.*;
public interface RemoteInterface extends Remote
{
public int add(int x,int y)throws RemoteException;
}
In the example above, add(int x,int y) is a remote method of the remote interface RemoteInterface. All
methods defined in the remote interface are required to state that they throw a RemoteException. A
RemoteException represents communication-related exceptions that may occur during the execution of
a remote method call.
The implementation is referred to as the remote object. The implementation class extends
UnicastRemoteObject to link into the RMI system. This is not a requirement. A class that does not
extend UnicastRemoteObject may use its exportObject() method to be linked into RMI. When a class
extends UnicastRemoteObject, it must provide a constructor declaring that it may throw a
RemoteException object. When this constructor calls super(), it activates code in UnicastRemoteObject,
which performs the RMI linking and remote object initialization.
The server creates the remote object, registers it under some arbitrary name, then waits for remote
requests. The java.rmi.registry.LocateRegistry class allows the RMI registry service (provided as part of
the JVM) to be started within the code by calling its createRegistry method.
This could have also been achieved by typing the following at a command prompt: start rmiregistry. The
default port for RMI is 1099. The java.rmi.registry.Registry class provides two
methods for binding objects to the registry.
Naming.bind("ArbitraryName", remoteObj); throws an Exception if an object is already bound under
the "ArbitrayName. "
Naming.rebind ("ArbitraryName", remoteObj); binds the object under the "ArbitraryName" if it does
not exist or overwrites the object that is bound.
The example above acts as a server that creates a ServerImplements object and makes it available to
clients by binding it under a name of "SERVICE ".
NOTE: If both the client and the server are running Java SE 5 or higher, no additional work is needed on
the server side. Simply compile the RemoteInterface.java, ServerImplements.java, and
AdditionServer.java, and the server can then be started. The reason for this is the introduction in Java
SE 5 of dynamic generation of stub classes. Java SE 5 adds support for the dynamic generation of stub
classes at runtime, eliminating the need to use the RMI stub compiler, rmic, to pre-generate stub classes
for remote objects.
• Note that rmic must still be used to pre-generate stub classes for remote objects that need to support
clients running on earlier versions.
Pros cons
Portable across many platforms Tied only to platforms with Java support
Can introduce new code to foreign JVMs Security threats with remote code execution, and
limitations on functionality enforced by security
restrictions.
Java developers may already have experience with Learning curve for developers that have no RMI
RMI (available since JDK1.02) experience is comparable with CORBA
Existing systems may already use RMI - the cost Can only operate with Java systems - no support
and time to convert to a new technology may be for legacy systems written in C++, Ada, Fortran,
prohibitive Cobol, and others (including future languages).
CORBA, or Common Object Request Broker Architecture, is a standard architecture for distributed
object systems. It allows a distributed, heterogeneous collection of objects to interoperate.
The OMG
The Object Management Group (OMG) is responsible for defining CORBA. The OMG comprises over 700
companies and organizations, including almost all the major vendors and developers of distributed
object technology, including platform, database, and application vendors as well as software tool and
corporate developers.
CORBA Architecture
CORBA defines an architecture for distributed objects. The basic CORBA paradigm is that of a request for
services of a distributed object. Everything else defined by the OMG is in terms of this basic paradigm.
The ORB
The ORB is the distributed service that implements the request to the remote object. It locates the
remote object on the network, communicates the request to the object, waits for the results and when
available communicates those results back to the client.
The ORB implements location transparency. Exactly the same request mechanism is used by the client
and the CORBA object regardless of where the object is located. It might be in the same process with the
client, down the hall or across the planet. The client cannot tell the difference.
The ORB implements programming language independence for the request. The client issuing the
request can be written in a different programming language from the implementation of the CORBA
object. The ORB does the necessary translation between programming languages. Language bindings are
defined for all popular programming languages.
Object life cycle Defines how CORBA objects are created, removed, moved, and
copied
Naming Defines how CORBA objects can have friendly symbolic names
Concurrency Control Provides a locking service for CORBA objects in order to ensure
serializable access
CORBA Products
CORBA is a specification; it is a guide for implementing products. Several vendors provide CORBA
products for various programming languages. The CORBA products that support the Java programming
language include:
The Java 2 ORB The Java 2 ORB comes with Sun's Java 2 SDK. It is missing
several features.
VisiBroker for Java A popular Java ORB from Inprise Corporation. VisiBroker is also
embedded in other products. For example, it is the ORB that is
embedded in the Netscape Communicator browser.
Various free or shareware ORBs CORBA implementations for various languages are available for
download on the web from various sources.
CORBA pros and cons
CORBA is gaining strong support from developers, because of its ease of use, functionality, and
portability across language and platform. CORBA is particularly important in large organizations, where
many systems must interact with each other, and legacy systems can't yet be retired. CORBA provides
the connection between one language and platform and another - its only limitation is that a language
must have a CORBA implementation written for it. CORBA also appears to have a performance increase
over RMI, which makes it an attractive option for systems that are accessed by users who require real-
time interaction.
Pros Cons
Services can be written in many different Describing services require the use of an interface
languages, executed on many different definition language (IDL) which must be learned.
platforms, and accessed by any language Implementing or using services require an IDL mapping
with an interface definition language (IDL) to your required language - writing one for a language
mapping that isn't supported would take a large amount of work.
With IDL, the interface is clearly separated IDL to language mapping tools create code stubs based
from implementation, and developers can on the interface - some tools may not integrate new
create different implementations based on changes with existing code.
the same interface.
CORBA supports primitive data types, and a CORBA does not support the transfer of objects, or code.
wide range of data structures, as parameters
CORBA is ideally suited to use with legacy The future is uncertain - if CORBA fails to achieve
systems, and to ensure that applications sufficient adoption by industry, then CORBA
written now will be accessible in the future. implementations become the legacy systems.
CORBA is an easy way to link objects and Some training is still required, and CORBA specifications
systems together. are still in a state of flux.