exception-handling€¦  · web viewthe java thread model. the java run-time system depends on...

66
Exception-Handling A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed. Exceptions can be generated by the Java run-time system, or they can be manually generated by our code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method. All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses that partition exceptions into two distinct branches. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. This is also the class that we will subclass to create our own custom exception types. The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal circumstances by our program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error. What happens if an exception occurs: Lets take the following java code written in Prog.java class Prog { public static void main(String args[]) { int d = 0; int a = 42 / d; }

Upload: others

Post on 01-Aug-2020

19 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

Exception-Handling

A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed. Exceptions can be generated by the Java run-time system, or they can be manually generated by our code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method.

All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses that partition exceptions into two distinct branches.

One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. This is also the class that we will subclass to create our own custom exception types.

The other branch is topped by Error, which defines exceptions that are not expected to be caught under normal circumstances by our program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error.

What happens if an exception occurs: Lets take the following java code written in Prog.java

class Prog {

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. Any exception that is not caught by our program will ultimately be processed by the default handler. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.Here is the output generated when this example is executed.

java.lang.ArithmeticException: / by zero at Prog.main(Prog.java:6)This can be managed by java exception handling mechanism. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Lets take a java program ExceptionProg.java

Page 2: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

class MyException extends Exception{

String toString(){

return “MyException: operand in * is zero”;}

}class ExceptionGenerator{

void multiply(int a, int b) throws MyException{

if(a==0 || b==0)throw new MyException();

elseSystem.out.print(“The result is ”+a*b);

}}class ExceptionDemo{

public static void main(String s[]){

ExceptionGenerator eg=new ExceptionGenerator( );int x, y, z; x=15;y=0;try{

z=x/y;System.out.print(“Divison is:” + z);try{

eg.multiply(x,y);}catch(MyException me){

System.out.print(“Exception:”+me);}System.out.print(“out of inner try block”);

}catch(ArithmeticException ae){

System.out.print(“Exception:”+me);

}finally{

System.out.print(“This line will definitely run”);}System.out.print(“out of outer try block”);System.out.print(“out of main”);

}

Page 3: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

}

Java’s Built-in Exceptions

Java’s Unchecked RuntimeException SubclassesException MeaningArithmeticException Arithmetic error, such as divide-by-zero.

ArrayIndexOutOfBoundsException Array index is out-of-bounds.

ArrayStoreException Assignment to an array element of an incompatible type.

ClassCastException Invalid cast.

IllegalArgumentException Illegal argument used to invoke a method.

IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.

IllegalStateException Environment or application is in incorrect state.

IllegalThreadStateException Requested operation not compatible with current thread state.

IndexOutOfBoundsException Some type of index is out-of-bounds.

NegativeArraySizeException Array created with a negative size.

NullPointerException Invalid use of a null reference.

NumberFormatException Invalid conversion of a string to a numeric format.

SecurityException Attempt to violate security.

StringIndexOutOfBounds Attempt to index outside the bounds of a string.

UnsupportedOperationException An unsupported operation was encountered.

Java’s Checked Exceptions Defined in java.langException MeaningClassNotFoundException Class not found.

CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface.

IllegalAccessException Access to a class is denied.

InstantiationException Attempt to create an object of an abstract class or interface.

InterruptedException One thread has been interrupted by another thread.

NoSuchFieldException A requested field does not exist.

NoSuchMethodException A requested method does not exist.

Page 4: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

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.There are two distinct types of multitasking: process-based and thread-based. Process Based: A process is, in essence, a program that is executing. Thus, process-based multitasking is the feature that allows our computer to run two or more programs concurrently. For example, process-based multitasking enables we to run the Java compiler at the same time that we are using a text editor. In process-based multitasking, a program is the smallest unit of code that can be dispatched by the scheduler.Thread Based: In a thread-based multitasking environment, the thread is the smallest unit of dispatchable code. This means that a single program can perform two or more tasks simultaneously. For instance, a text editor can format text at the same time that it is printing, as long as these two actions are being performed by two separate threads. Thus, process-based multitasking deals with the “big picture,” and thread-based multitasking handles the details.Multitasking threads require less overhead than multitasking processes, because

Processes are heavyweight tasks that require their own separate address spaces. Threads, on the other hand, are lightweight. They share the same address space and cooperatively share the same heavyweight process.

Interprocess communication is expensive and limited. Context switching from one process to another is also costly. Interthread communication is inexpensive, and context switching from one thread to the next is low cost.

While Java programs make use of process-based multitasking environments, process-based multitasking is not under the control of Java. However, multithreaded multitasking is.

The Java Thread ModelThe Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading in mind.Single-threaded systems use an approach called an event loop with polling. In this model, a single thread of control runs in an infinite loop, polling a single event queue to decide what to do next. Once this polling mechanism returns with, say, a signal that a network file is ready to be read, then the event loop dispatches control to the appropriate event handler. Until this event handler returns, nothing else can happen in the system. This wastes CPU time.The benefit of Java’s multithreading is that the main loop/polling mechanism is eliminated. One thread can pause without stopping other parts of our program. For example, the idle time created when a thread reads data from a network or waits for user input can be utilized elsewhere. Multithreading allows animation loops to sleep for a second between each frame without causing the whole system to pause. When a thread blocks in a Java program, only the single thread that is blocked pauses. All other threads continue to run.Threads exist in several states. A thread can be running. It can be ready to run as soon as it gets CPU time. A running thread can be suspended, which temporarily suspends its activity. A suspended thread can then be resumed, allowing it to pick up where it left off. A thread can be blocked when waiting for a resource. At any time, a thread can be terminated, which halts its execution immediately. Once terminated, a thread cannot be resumed.

Page 5: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

Thread PrioritiesJava assigns to each thread a priority that determines how that thread should be treated with respect to the others. Thread priorities are integers that specify the relative priority of one thread to another. As an absolute value, a priority is meaningless; a higher-priority thread doesn’t run any faster than a lower-priority thread if it is the only thread running. Instead, a thread’s priority is used to decide when to switch from one running thread to the next. This is called a context switch. The rules that determine when a context switch takes place are simple:■ A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or blocking on pending I/O. In this scenario, all other threads are examined, and the highest-priority thread that is ready to run is given the CPU.■ A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that does not yield the processor is simply preempted—no matter what it is doing—by a higher-priority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking.

SynchronizationBecause multithreading introduces an asynchronous behavior to our programs, there must be a way for we to enforce synchronicity when we need it. For example, if we want two threads to communicate and share a complicated data structure, such as a linked list, we need some way to ensure that they don’t conflict with each other. That is, we must prevent one thread from writing data while another thread is in the middle of reading it. For this purpose, Java implements an elegant twist on an age-old model of interprocess synchronization: the monitor. The monitor is a control mechanism first defined by C.A.R. Hoare. We can think of a monitor as a very small box that can hold only one thread. Once a thread enters a monitor, all other threads must wait until that thread exits the monitor. In this way, a monitor can be used to protect a shared asset from being manipulated by more than one thread at a time.Most multithreaded systems expose monitors as objects that our program must explicitly acquire and manipulate. Java provides a cleaner solution. There is no class “Monitor”; instead, each object has its own implicit monitor that is automatically entered when one of the object’s synchronized methods is called. Once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object. This enables we to write very clear and concise multithreaded code, because synchronization support is built in to the language.

MessagingAfter we divide our program into separate threads, we need to define how they will communicate with each other. When programming with most other languages, we must depend on the operating system to establish communication between threads. This, of course, adds overhead. By contrast, Java provides a clean, low-cost way for two or more threads to talk to each other, via calls to predefined methods that all objects have. Java’s messaging system allows a thread to enter a synchronized method on an object, and then wait there until some other thread explicitly notifies it to come out.

The Thread Class and the Runnable InterfaceJava’s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable. Thread encapsulates a thread of execution. Since we can’t directly refer to the ethereal state of a running thread, we will deal with it through its proxy, the Thread instance that spawned it. To create a new thread, our program will either extend Thread or implement the Runnable interface.

Page 6: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

The Thread class defines several methods that help manage threads. The ones that will be used in this chapter are shown here:Method MeaninggetName Obtain a thread’s name.getPriority Obtain a thread’s priority.isAlive Determine if a thread is still running.join Wait for a thread to terminate.run Entry point for the thread.sleep Suspend a thread for a period of time.start Start a thread by calling its run method.

The Main ThreadWhen a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program, because it is the one that is executed when our program begins. The main thread is important for two reasons:

It is the thread from which other “child” threads will be spawned. Often it must be the last thread to finish execution because it performs various

shutdown actions. .ANGUAGE

Creating a ThreadIn the most general sense, we create a thread by instantiating an object of type Thread. Java defines two ways in which this can be accomplished:■ We can implement the Runnable interface.■ We can extend the Thread class, itself.

Implementing Runnable

Runnable abstracts a unit of executable code. To implement Runnable, a class need only implement a single method called run( ), which is declared like this:

public void run( )

Inside run( ), we 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. The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within our program. This thread will end when run( ) returns. After we create a class that implements Runnable, we will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:

Thread(Runnable threadOb, String threadName)

In this constructor, threadOb is an instance of a class that implements the Runnable interface. This defines where execution of the thread will begin. The name of the new thread is specified by threadName.After the new thread is created, it will not start running until we call its start( ) method, which is declared within Thread. In essence, start( ) executes a call to run( ).The start( ) method is shown here:

void start( )

Page 7: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

// Create a second thread.class NewThread implements Runnable {

Thread t;NewThread() {

// Create a new, second threadt = new Thread(this, "Demo Thread");System.out.println("Child thread: " + t);t.start(); // Start the thread

}// This is the entry point for the second thread.public void run() {

try {

for(int i = 5; i > 0; i--) {

System.out.println("Child Thread: " + i);Thread.sleep(500);

}} catch (InterruptedException e) {

System.out.println("Child interrupted.");}System.out.println("Exiting child thread.");

}}class ThreadDemo {

public static void main(String args[]) {

new NewThread(); // create a new threadtry {

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.");

}}

Page 8: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

Extending Thread

The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread. Here is the preceding program rewritten to extend Thread:

// Create a second thread by extending Threadclass NewThread extends Thread {

NewThread() {

// Create a new, second threadsuper("Demo Thread");System.out.println("Child thread: " + this);start(); // Start the thread

}// This is the entry point for the second thread.public void run()

{try {

for(int i = 5; i > 0; i--) {

System.out.println("Child Thread: " + i);Thread.sleep(500);

}} catch (InterruptedException e) {

System.out.println("Child interrupted.");}System.out.println("Exiting child thread.");

}}class ExtendThread {

public static void main(String args[]) {

new NewThread(); // create a new threadtry {

for(int i = 5; i > 0; i--) {

System.out.println("Main Thread: " + i);Thread.sleep(1000);

}} catch (InterruptedException e)

Page 9: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

{System.out.println("Main thread interrupted.");

}System.out.println("Main thread exiting.");

}}

This program generates the same output as the preceding version. As we can see, the child thread is created by instantiating an object of NewThread, which is derived from Thread.Notice the call to super( ) inside NewThread. This invokes the following form of the Thread constructor:

public Thread(String threadName)

Here, threadName specifies the name of the thread.

Using isAlive( ) and join( )

Two ways exist to determine whether a thread has finished. First, we can call isAlive( ) on the thread. This method is defined by Thread, and its general form is shown here:

final boolean isAlive( )

The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false otherwise. While isAlive( ) is occasionally useful, the method that we will more commonly use to wait for a thread to finish is called join( ), shown here:

final void join( ) throws InterruptedException

This method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it.

// Using join() to wait for threads to finish.class NewThread implements Runnable {

String name; // name of threadThread t;NewThread(String threadname) {

name = threadname;t = new Thread(this, name);System.out.println("New thread: " + t);t.start(); // Start the thread

}// This is the entry point for thread.public void run() {

try {

Page 10: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

for(int i = 5; i > 0; i--) {

System.out.println(name + ": " + i);Thread.sleep(1000);

}} catch (InterruptedException e){

System.out.println(name + " interrupted.");}System.out.println(name + " exiting.");

}}class DemoJoin {

public static void main(String args[]) {

NewThread ob1 = new NewThread("One");NewThread ob2 = new NewThread("Two");NewThread ob3 = new NewThread("Three");System.out.println("Thread One is alive: " + ob1.t.isAlive());System.out.println("Thread Two is alive: " + ob2.t.isAlive());System.out.println("Thread Three is alive: " + ob3.t.isAlive());// wait for threads to finishtry {

System.out.println("Waiting for threads to finish.");ob1.t.join();ob2.t.join();ob3.t.join();

} catch (InterruptedException e)

{System.out.println("Main thread Interrupted");

}System.out.println("Thread One is alive: " + ob1.t.isAlive());System.out.println("Thread Two is alive: " + ob2.t.isAlive());System.out.println("Thread Three is alive: " + ob3.t.isAlive());System.out.println("Main thread exiting.");

}}

SynchronizationWhen 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 we will see, Java provides unique, language-level support for it.Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a given time. When a thread acquires a lock, it is said to have

Page 11: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

entered the monitor. All other threads attempting to enter the locked monitor will be suspended until the first thread exits the monitor. These other threads are said to be waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it so desires.If we have worked with synchronization when using other languages, such as C or C++, we know that it can be a bit tricky to use. This is because most languages do not, themselves, support synchronization. Instead, to synchronize threads, our programs need to utilize operating system primitives. Fortunately, because Java implements synchronization through language elements, most of the complexity associated with synchronization has been eliminated.We can synchronize our code in either of two ways. Both involve the use of the synchronized keyword, and both are examined here.

Using Synchronized MethodsSynchronization is easy in Java, because all objects have their own implicit monitor associated with them. To enter an object’s monitor, just call a method that has been modified with the synchronized keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any other synchronized method) on the same instance have to wait. To exit the monitor and relinquish control of the object to the next waiting thread, the owner of the monitor simply returns from the synchronized method.To understand the need for synchronization, let’s begin with a simple example that does not use it—but should. The following program has three simple classes. The first one, Callme, has a single method named call( ). The call( ) method takes a String parameter called msg. This method tries to print the msg string inside of square brackets. The interesting thing to notice is that after call( ) prints the opening bracket and the msg string, it calls Thread.sleep(1000), which pauses the current thread for one second.The constructor of the next class, Caller, takes a reference to an instance of the Callme class and a String, which are stored in target and msg, respectively. The constructor also creates a new thread that will call this object’s run( ) method. The thread is started immediately. The run( ) method of Caller calls the call( ) method on the target instance of Callme, passing in the msg string. Finally, the Synch class starts by creating a single instance of Callme, and three instances of Caller, each with a unique message string. The same instance of Callme is passed to each Caller.

// This program is not synchronized.class Callme {

void call(String msg) {

System.out.print("[" + msg);try {

Thread.sleep(1000);} catch(InterruptedException e) {

System.out.println("Interrupted");}System.out.println("]");

Page 12: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

}}class Caller implements Runnable {

String msg;Callme target;Thread t;public Caller(Callme targ, String s) {

target = targ;msg = s;t = new Thread(this);t.start();

}public void run() {

target.call(msg);}THE JAVA LANGUAGE

}class Synch {

public static void main(String args[]) {

Callme target = new Callme();Caller ob1 = new Caller(target, "Hello");Caller ob2 = new Caller(target, "Synchronized");Caller ob3 = new Caller(target, "World");// wait for threads to endtry {

ob1.t.join();ob2.t.join();ob3.t.join();

} catch(InterruptedException e) {System.out.println("Interrupted");}

}}

Here is the output produced by this program:

Hello[Synchronized[World]]]

As we can see, by calling sleep( ), the call( ) method allows execution to switch to another thread. This results in the mixed-up output of the three message strings. In this program, nothing exists to stop all three threads from calling the same method, on the same object, at the same time. This is known as a race condition, because the three

Page 13: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

threads are racing each other to complete the method. This example used sleep( ) to make the effects repeatable and obvious. In most situations, a race condition is more subtle and less predictable, because we can’t be sure when the context switch will occur. This can cause a program to run right one time and wrong the next.To fix the preceding program, we must serialize access to call( ). That is, we must restrict its access to only one thread at a time. To do this, we simply need to precede call( )’s definition with the keyword synchronized, as shown here:

class Callme {synchronized void call(String msg) {...

This prevents other threads from entering call( ) while another thread is using it. After synchronized has been added to call( ), the output of the program is as follows:

[Hello][Synchronized][World]

Any time that we have a method, or group of methods, that manipulates the internal state of an object in a multithreaded situation, we should use the synchronized keyword to guard the state from race conditions. Remember, once a thread enters any synchronized method on an instance, no other thread can enter any other synchronized method on the same instance. However, nonsynchronized methods on that instance will continue to be callable.

The synchronized StatementWhile creating synchronized methods within classes that we create is an easy and effective means of achieving synchronization, it will not work in all cases. To understand why, consider the following. Imagine that we want to synchronize access to objects of a class that was not designed for multithreaded access. That is, the class does not use synchronized methods. Further, this class was not created by we, but by a third party, and we do not have access to the source code. Thus, we can’t add synchronized to the appropriate methods within the class. How can access to an object of this class be synchronized? Fortunately, the solution to this problem is quite easy: We simply put calls to the methods defined by this class inside a synchronized block.This is the general form of the synchronized statement:synchronized(object) {// statements to be synchronized}Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object’s monitor.Here is an alternative version of the preceding example, using a synchronized block within the run( ) method:

// This program uses a synchronized block.class Callme {

void call(String msg) {

Page 14: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

System.out.print("[" + msg);try {THE JAVA LANGUAGE

Thread.sleep(1000);} catch (InterruptedException e) {

System.out.println("Interrupted");}System.out.println("]");

}}class Caller implements Runnable {

String msg;Callme target;Thread t;public Caller(Callme targ, String s) {

target = targ;msg = s;t = new Thread(this);t.start();

}// synchronize calls to call()public void run() {

synchronized(target) { // synchronized block

target.call(msg);}

}}class Synch1 {

public static void main(String args[]) {

Callme target = new Callme();Caller ob1 = new Caller(target, "Hello");Caller ob2 = new Caller(target, "Synchronized");Caller ob3 = new Caller(target, "World");// wait for threads to endtry {

ob1.t.join();ob2.t.join();ob3.t.join();

} catch(InterruptedException e) {

System.out.println("Interrupted");

Page 15: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

}}

}

Here, the call( ) method is not modified by synchronized. Instead, the synchronized statement is used inside Caller’s run( ) method. This causes the same correct output as the preceding example, because each thread waits for the prior one to finish before proceeding.

Interthread CommunicationMultithreading replaces event loop programming by dividing our tasks into discrete and logical units. Threads also provide a secondary benefit: they do away with polling. Polling is usually implemented by a loop that is used to check some condition repeatedly. Once the condition is true, appropriate action is taken. This wastes CPU time.To avoid polling, Java includes an elegant interprocess communication mechanism via the wait( ), notify( ), and notifyAll( ) methods. These methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from within a synchronized context.

wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).

notify( ) wakes up the first thread that called wait( ) on the same object. notifyAll( ) wakes up all the threads that called wait( ) on the same object. The

highest priority thread will run first.

These methods are declared within Object, as shown here:final void wait( ) throws InterruptedExceptionfinal void notify( )final void notifyAll( )

Example: Consider the classic queuing problem, where one thread is producing some data and another is consuming it. To make the problem more interesting, suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waited for the producer to produce. Once the producer was finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on.

// A correct implementation of a producer and consumer.class Q {

int n;boolean valueSet = false;synchronized int get() {

if(!valueSet)try {

wait();} catch(InterruptedException e) {

System.out.println("InterruptedException caught");

Page 16: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

}System.out.println("Got: " + n);valueSet = false;notify();return n;

}synchronized void put(int n) {

if(valueSet)try {

wait();} catch(InterruptedException e) {

System.out.println("InterruptedException caught");}this.n = n;E JAVA LANGUAGEvalueSet = true;System.out.println("Put: " + n);notify();

}}class Producer implements Runnable {

Q q;Producer(Q q) {

this.q = q;new Thread(this, "Producer").start();

}public void run() {

int i = 0;while(true) {

q.put(i++);}

}}class Consumer implements Runnable {

Q q;Consumer(Q q) {

this.q = q;new Thread(this, "Consumer").start();

}public void run() {

while(true)

Page 17: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

{q.get();

}}

}class PCFixed {

public static void main(String args[]) {

Q q = new Q();new Producer(q);new Consumer(q);System.out.println("Press Control-C to stop.");

}}

Deadlock

A special type of error that we need to avoid that relates specifically to multitasking is deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects. For example, suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. If the thread in X tries to call any synchronized method on Y, it will block as expected. However, if the thread in Y, in turn, tries to call any synchronized method on X, the thread waits forever, because to access X, it would have to release its own lock on Y so that the first thread could complete. Deadlock is a difficult error to debug for two reasons:

In general, it occurs only rarely, when the two threads time-slice in just the right way.

It may involve more than two threads and two synchronized objects. (That is, deadlock can occur through a more convoluted sequence of events than just described.)

Page 18: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

I/O Basics

Most real applications of Java are not text-based, console programs. Rather, they are graphically oriented applets that rely upon Java’s Abstract Window Toolkit (AWT) for interaction with the user. Java’s support for console I/O is limited and somewhat awkward to use—even in simple example programs. Text-based console I/O is just not very important to Java programming. Java’s I/O system is cohesive and consistent.

StreamsJava programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. All streams behave in the same manner, even if the actual physical devices to which they are linked differ. Thus, the same I/O classes and methods can be applied to any type of device. This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Likewise, an output stream may refer to the console, a disk file, or a network connection. Streams are a clean way to deal with input/output without having every part of our code understand the difference between a keyboard and a network, for example. Java implements streams within class hierarchies defined in the java.io package.

Byte Streams and Character StreamsJava 2 defines two types of streams: byte and character. Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. Character streams provide a convenient means for handling input and output of characters. They use Unicode and, therefore, can be internationalized. At the lowest level, all I/O is byte-oriented. The character-based streams simply provide a convenient and efficient means for handling characters. The Byte Stream ClassesByte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. Each of these abstract classes has several concrete subclasses, that handle the differences between various devices, such as disk files, network connections, and even memory buffers. The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important are read( ) and write( ), which, respectively, read and write bytes of data. Both methods are declared as abstract inside InputStream and OutputStream. They are overridden by derived stream classes.

The Character Stream ClassesCharacter streams are defined by using two class hierarchies. At the top are two abstract classes, Reader and Writer. These abstract classes handle Unicode character streams. Java has several concrete subclasses of each of these. The abstract classes Reader and Writer define several key methods that the other stream classes implement. Two of the most important methods are read( ) and write( ), which read and write characters of data, respectively. These methods are overridden by derived stream classes.

Page 19: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

The Byte Stream Classes

Stream Class MeaningBufferedInputStream Buffered input streamBufferedOutputStream Buffered output streamByteArrayInputStream Input stream that reads from a byte arrayByteArrawetputStream Output stream that writes to a byte arrayDataInputStream An input stream that contains methods for reading

the Java standard data typesDataOutputStream An output stream that contains methods for writing

the Java standard data typesFileInputStream Input stream that reads from a fileFileOutputStream Output stream that writes to a fileFilterInputStream Implements InputStreamFilterOutputStream Implements OutputStreamInputStream Abstract class that describes stream inputOutputStream Abstract class that describes stream outputPipedInputStream Input pipePipedOutputStream Output pipePrintStream Output stream that contains print( ) and println( )PushbackInputStream Input stream that supports one-byte “unget,” which

returns a byte to the input streamRandomAccessFile Supports random access file I/OSequenceInputStream Input stream that is a combination of two or more

input streams that will be read sequentially, one after the other

The Character Stream I/O ClassesTHE JAVA LANGUAGEStream Class MeaningBufferedReader Buffered input character streamBufferedWriter Buffered output character streamCharArrayReader Input stream that reads from a character arrayCharArrayWriter Output stream that writes to a character arrayFileReader Input stream that reads from a fileFileWriter Output stream that writes to a fileFilterReader Filtered readerFilterWriter Filtered writerInputStreamReader Input stream that translates bytes to charactersLineNumberReader Input stream that counts linesOutputStreamWriter Output stream that translates characters to bytesPipedReader Input pipePipedWriter Output pipePrintWriter Output stream that contains print( ) and println( )PushbackReader Input stream that allows characters to be returned to

the input streamReader Abstract class that describes character stream inputStringReader Input stream that reads from a stringStringWriter Output stream that writes to a stringWriter Abstract class that describes character stream output

Page 20: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

Predefined Streams

All Java programs automatically import the java.lang package. This package defines a class called System, which encapsulates several aspects of the run-time environment. System contains three predefined stream variables, in, out, and err. These fields are declared as public and static within System.

System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by

default. However, these streams may be redirected to any compatible I/O device.System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream.

Reading Console Input Java does not have a generalized console input method that parallels the standard

Cfunction scanf( ) or C++ input operators.In Java, console input is accomplished by reading from System.in. To obtain a character-based stream that is attached to the console, we wrap System.in in a BufferedReader object, to create a character stream. BuffereredReader supports a buffered input stream.

BufferedReader(Reader inputReader)

Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor:

InputStreamReader(InputStream inputStream)

To read a character from a BufferedReader, use read( ).

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.

// Use a BufferedReader to read characters from the console.import java.io.*;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.");THE JAVA LANGUAGE

// read charactersdo {

c = (char) br.read();System.out.println(c);

Page 21: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

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

}

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

// Read a string from console using a BufferedReader.import java.io.*;class BRReadLines {

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

// create a BufferedReader using System.inBufferedReader br = new BufferedReader(new InputStreamReader(System.in));String str;System.out.println("Enter lines of text.");System.out.println("Enter 'stop' to quit.");do{

str = br.readLine();System.out.println(str);

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

}

Writing Console Output

Console output is most easily accomplished with print( ) and println( ), described earlier, which are used in most of the examples in this book. These methods are defined by the class PrintStream (which is the type of the object referenced by System.out). Even though System.out is a byte stream, using it for simple program output is still acceptable. However, a character-based alternative is described in the next section.Because PrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ). Thus, write( ) can be used to write to the console. The simplest form of write( ) defined by PrintStream is shown here:

void write(int byteval)

This method writes to the stream the byte specified by byteval. Although byteval is declared as an integer, only the low-order eight bits are written. Here is a short example that uses write( ) to output the character “A” followed by a newline to the screen:

// Demonstrate System.out.write().class WriteDemo {

public static void main(String args[]) {

int b;

Page 22: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

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

}}

The PrintWriter ClassAlthough using System.out to write to the console is still permissible under Java, its use is recommended mostly for debugging purposes or for sample programs, such as those found in this book. For real-world programs, the recommended method of writing to the console when using Java is through a PrintWriter stream. PrintWriter is one of the character-based classes. Using a character-based class for console output makes it easier to internationalize our program.PrintWriter defines several constructors. The one is shown here:

PrintWriter(OutputStream outputStream, boolean flushOnNewline)

Here, outputStream is an object of type OutputStream, and flushOnNewline controls whether Java flushes the output stream every time a println( ) method is called. If flushOnNewline is true, flushing automatically takes place. If false, flushing is not automatic.PrintWriter supports the print( ) and println( ) methods for all types including Object. Thus, we can use these methods in the same way as they have been used with System.out. If an argument is not a simple type, the PrintWriter methods call the object’s toString( ) method and then print the result.To write to the console by using a PrintWriter, specify System.out for the output stream and flush the stream after each newline. For example, this line of code creates a PrintWriter that is connected to console output:

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

// Demonstrate PrintWriterimport java.io.*;public class PrintWriterDemo {

public static void main(String args[]) {

PrintWriter pw = new PrintWriter(System.out, true);pw.println("This is a string");int i = -7;pw.println(i);double d = 4.5e-7;pw.println(d);

}}

Page 23: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

Reading and Writing FilesJava provides a number of classes and methods that allow we to read and write files. In Java, all files are byte-oriented, and Java provides methods to read and write bytes from and to a file. However, Java allows we to wrap a byte-oriented file stream within a character-based object.Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files. To open a file, we create an object of one of these classes, specifying the name of the file as an argument to the constructor. One of the constructors is: THE JAVA LANGUAGEFileInputStream(String fileName) throws FileNotFoundExceptionFileOutputStream(String fileName) throws FileNotFoundException

Here, fileName specifies the name of the file that we want to open. When we create an input stream, if the file does not exist, then FileNotFoundException is thrown. For output streams, if the file cannot be created, then FileNotFoundException is thrown. When an output file is opened, any preexisting file by the same name is destroyed.

When we are done with a file, we should close it by calling close( ). It is defined by both FileInputStream and FileOutputStream, as shown here:

void close( ) throws IOException

To read from a file, we can use a version of read( ) that is defined within FileInputStream. The one that we will use is shown here:

int read( ) throws IOException

Each time that it is called, it reads a single byte from the file and returns the byte as an integer value. read( ) returns –1 when the end of the file is encountered. It can throw an IOException.

/* Display a text file. To use this program, specify the name of the file that we want to see. For example, to see a file called TEST.TXT, use the following command line. java ShowFile TEST.TXT */

import java.io.*;class ShowFile {

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

int i;FileInputStream fin;try {

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

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

Page 24: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

} catch(ArrayIndexOutOfBoundsException e) {

System.out.println("Usage: ShowFile File");return;

}// read characters until EOF is encountereddo {

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

} while(i != -1);fin.close();

}}

To write to a file, we will use the write( ) method defined by FileOutputStream. Its simplest form is shown here:

void write(int byteval) throws IOException

This method writes the byte specified by byteval to the file. Although byteval is declared as an integer, only the low-order eight bits are written to the file. If an error occurs during writing, an IOException is thrown. The next example uses write( ) to copy a text file:

/* Copy a text file. To use this program, specify the name of the source file and the destination file. For example, to copy a file called FIRST.TXT to a file called SECOND.TXT, use the following command line. java CopyFile FIRST.TXT SECOND.TXT */

import java.io.*;class CopyFile {

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

int i;FileInputStream fin;FileOutputStream fout;try {

// open input filetry {

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

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

}// open output file

Page 25: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

try {

fout = new FileOutputStream(args[1]);} catch(FileNotFoundException e) {

System.out.println("Error Opening Output File");return;

}} catch(ArrayIndexOutOfBoundsException e) {

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

}// Copy Filetry {

do {

i = fin.read();if(i != -1) fout.write(i);

} while(i != -1);} catch(IOException e) {

System.out.println("File Error");}fin.close();fout.close();

}}

Java uses its exception handling mechanism. This makes file handling cleaner, It also enables Java to easily differentiate the end-of-file condition from file errors when input is being performed. In Java, errors are passed to our program via exceptions, not by values returned by read( ). Thus, when read( ) returns –1, it means only one thing: the end of the file has been encountered.

Serialization

Serialization is the process of writing the state of an object to a byte stream. This is useful when we want to save the state of our program to a persistent storage area, such as a file. At a later time, we may restore these objects by using the process of deserialization.Serialization is also needed to implement Remote Method Invocation (RMI). RMI allows a Java object on one machine to invoke a method of a Java object on a different machine. An object may be supplied as an argument to that remote method. The sending machine serializes the object and transmits it. The receiving machine deserializes it.

Assume that an object to be serialized has references to other objects, which, in turn, have references to still more objects. This set of objects and the relationships among them

Page 26: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

form a directed graph. There may also be circular references within this object graph. That is, object X may contain a reference to object Y, and object Y may contain a reference back to object X. Objects may also contain references to themselves.

The object serialization and deserialization facilities have been designed to work correctly in these scenarios. If we attempt to serialize an object at the top of an object graph, all of the other referenced objects are recursively located and serialized.

Similarly, during the process of deserialization, all of these objects and their references are correctly restored. An overview of the interfaces and classes that support serialization follows.

Serializable

Only an object that implements the Serializable interface can be saved and restored by the serialization facilities. The Serializable interface defines no members. It is simply used to indicate that a class may be serialized. If a class is serializable, all of its subclasses are also serializable.

Variables that are declared as transient are not saved by the serialization facilities. Also, static variables are not saved.THE JAVA LIBRARYExternalizable

The Java facilities for serialization and deserialization have been designed so that much of the work to save and restore the state of an object occurs automatically. However, there are cases in which the programmer may need to have control over these processes. For example, it may be desirable to use compression or encryption techniques. The Externalizable interface is designed for these situations.The Externalizable interface defines these two methods:

void readExternal(ObjectInput inStream) throws IOException, ClassNotFoundExceptionvoid writeExternal(ObjectOutput outStream) throws IOException

In these methods, inStream is the byte stream from which the object is to be read, and outStream is the byte stream to which the object is to be written.

Page 27: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

Applet Fundamentals

Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a Web document. After an applet arrives on the client, it has limited access to resources, so that it can produce an arbitrary multimedia user interface and run complex computations without introducing the risk of viruses or breaching data integrity.The Applet class is contained in the java.applet package. Applet contains several methods that give us detailed control over the execution of our applet. In addition, java.applet also defines three interfaces: AppletContext, AudioClip, and AppletStub.

The Applet ClassThe Applet class defines various methods. Applet provides all necessary support for applet execution, such as starting and stopping. It also provides methods that load and display images, and methods that load and play audio clips. Applet extends the AWT class Panel. In turn, Panel extends Container, which extends Component. These classes provide support for Java’s window-based, graphical interface. Thus, Applet provides all of the necessary support for window-based activities.

Let’s begin with the simple applet shown here:

import java.awt.*;import java.applet.*;public class SimpleApplet extends Applet {

public void paint(Graphics g) {

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

}

This applet begins with two import statements. The first imports the Abstract Window Toolkit (AWT) classes. Applets interact with the user through the AWT, not through the console-based I/O classes. The AWT contains support for a window-based, graphical interface. The AWT is quite large and sophisticated. The second import statement imports the applet package, which contains the class Applet. Every applet that we create must be a subclass of Applet.The next line in the program declares the class SimpleApplet. This class must be declared as public, because it will be accessed by code that is outside the program. Inside SimpleApplet, paint( ) is declared. This method is defined by the AWT and must be overridden by the applet. paint( ) is called each time that the applet must redisplay its output. This situation can occur for several reasons. For example, the window in which the applet is running can be overwritten by another window and then uncovered. Or, the applet window can be minimized and then restored. paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter contains the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required. Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This method outputs a string beginning at the specified X,Y location. It has the following general form:

Page 28: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

void drawString(String message, int x, int y)

Here, message is the string to be output beginning at x,y. In a Java window, the upper-leftcorner is location 0,0. The call to drawString( ) in the applet causes the message “A Simple Applet” to be displayed beginning at location 20,20. The applet does not have a main( ) method. Unlike Java programs, applets do not begin execution at main( ). In fact, most applets don’t even have a main( ) method. Instead, an applet begins execution when the name of its class is passed to an applet viewer or to a network browser. JAVA LANGUAGEAfter we enter the source code for SimpleApplet, compile in the same way that we have been compiling programs. However, running SimpleApplet involves a different process. In fact, there are two ways in which we can run an applet:

Executing the applet within a Java-compatible Web browser. Using an applet viewer, such as the standard SDK tool, appletviewer. An applet

viewer executes our applet in a window. This is generally the fastest and easiest way to test our applet.

Each of these methods is described next.

To execute an applet in a Web browser, we need to write a short HTML text file that contains the appropriate APPLET tag. Here is the HTML file that executes SimpleApplet:

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

The width and height statements specify the dimensions of the display area used by the applet. (The APPLET tag contains several other options that are examined more closely in Part II.) After we create this file, we can execute our browser and then load this file, which causes SimpleApplet to be executed.

To execute SimpleApplet with an applet viewer, we may also execute the HTML file shown earlier. For example, if the preceding HTML file is called RunApp.html, then the following command line will run SimpleApplet:

C:\>appletviewer RunApp.html

However, a more convenient method exists that we can use to speed up testing. Simply include a comment at the head of our Java source code file that contains the APPLET tag. By doing so, our code is documented with a prototype of the necessary HTML statements, and we can test our compiled applet merely by starting the applet viewer with our Java source code file. If we use this method, the SimpleApplet source file looks like this:

import java.awt.*;import java.applet.*;/*<applet code="SimpleApplet" width=200 height=60></applet>*/

Page 29: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

public class SimpleApplet extends Applet {

public void paint(Graphics g) {

THE JAVA LANGUAGEg.drawString("A Simple Applet", 20, 20);

}}

In general, we can quickly iterate through applet development by using these three steps:1. Edit a Java source file.2. Compile our program.3. Execute the applet viewer, specifying the name of our applet’s source file. The applet viewer will encounter the APPLET tag within the comment and execute our applet.

The window produced by SimpleApplet, as displayed by the applet viewer, is shown in the following illustration:

The key points that we should remember: Applets do not need a main( ) method. Applets must be run under an applet viewer or a Java-compatible browser. User I/O is not accomplished with Java’s stream I/O classes. Instead, applets use

the interface provided by the AWT.

THE JAVARYApplet Architecture

An applet is a window-based program. First, applets are event driven. An applet resembles a set of interrupt service routines. An applet waits until an event occurs. The AWT notifies the applet about an event by calling an event handler that has been provided by the applet. Once this happens, the applet must take appropriate action and then quickly return control to the AWT. This is a crucial point.For the most part, our applet should not enter a “mode” of operation in which it maintains control for an extended period. Instead, it must perform specific actions in response to events and then return control to the AWT run-time system. In those situations in which our applet needs to perform a repetitive task on its own (for example, displaying a scrolling message across its window), we must start an additional thread of execution. (We will see an example later in this chapter.)

Second, the user initiates interaction with an applet—not the other way around. As we know, in a nonwindowed program, when the program needs input, it will prompt the user and then call some input method, such as readLine( ). This is not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when he or she wants. These interactions are sent to the applet as events to which the applet must respond. For example, when the user clicks a mouse inside the applet’s window, a mouse-clicked event is generated. If the user presses a key while the applet’s window has input focus, a keypress event is generated. As we will see in later chapters, applets can contain various controls, such as push buttons and check boxes. When the user interacts with one of these controls, an event is generated.

Page 30: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

While the architecture of an applet is not as easy to understand as that of a console-based program, Java’s AWT makes it as simple as possible. If we have written programs for Windows, we know how intimidating that environment can be. Fortunately, Java’s AWT provides a much cleaner approach that is more quickly mastered.

An Applet SkeletonAll but the most trivial applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods—init( ), start( ), stop( ), and destroy( )—are defined by Applet. Another, paint( ), is defined by the AWT Component class. Default implementations for all of these methods are provided. Applets do not need to override those methods they do not use. However, only very simple applets will not need to define all of them. These five methods can be assembled into the skeleton shown here:

// An Applet skeleton.import java.awt.*;import java.applet.*;/*<applet code="AppletSkel" width=300 height=100></applet>*/public class AppletSkel extends Applet {

// Called first.public void init() {

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

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

// suspends execution}// Called when applet is terminated. This is the last method executed. public void destroy() {

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

// redisplay contents of window}

}

Page 31: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

Applet Initialization and TerminationWhen an applet begins, the AWT calls the following methods, in this sequence:

1. init( )2. start( )3. paint( )

When an applet is terminated, the following sequence of method calls takes place:1. stop( )2. destroy( )

init( )The init( ) method is the first method to be called. This is where we should initialize variables. This method is called only once during the run time of our applet.

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

paint( )The paint( ) method is called each time our applet’s output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and then restored. paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required.

stop( )The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another page, for example. When stop( ) is called, the applet is probably running. We should use stop( ) to suspend threads that don’t need to run when the applet is not visible. We can restart them when start( ) is called if the user returns to the page.

destroy( )The destroy( ) method is called when the environment determines that our applet needs to be removed completely from memory. At this point, we should free up any resources the applet may be using. The stop( ) method is always called before destroy( ).

Overriding update( )In some situations, our applet may need to override another method defined by the AWT, called update( ). This method is called when our applet has requested that a portion of its window be redrawn. The default version of update( ) first fills an applet with the default background color and then calls paint( ). If we fill the background using a different color in paint( ), the user will experience a flash of the default background each time update( ) is called—that is, whenever the window is repainted.One way to avoid this problem is to override the update( ) method so that it performs all necessary display activities. Then have paint( ) simply call update( ). Thus, for some applications, the applet skeleton will override paint( ) and update( ), as shown here:

Page 32: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

public void update(Graphics g) {

// redisplay our window, here.}public void paint(Graphics g) {

update(g);}

To set the background color of an applet’s window, use setBackground( ). To set the foreground color (the color in which text is shown, for example), use setForeground( ).These methods are defined by Component, and they have the following general forms:

void setBackground(Color newColor)void setForeground(Color newColor)

Here, newColor specifies the new color. The class Color defines the constants shown here that can be used to specify colors:

Color.black Color.magenta Color.blue Color.orange Color.cyan Color.pink Color.darkGray Color.redColor.gray Color.white Color.green Color.yellowColor.lightGray

A good place to set the foreground and background colors is in the init( ) method. We can change these colors as often as necessary during the execution of our applet. The default foreground color is black. The default background color is light gray.

We can obtain the current settings for the background and foreground colors by calling getBackground( ) and getForeground( ), respectively. They are also defined by Component and are shown here:

Color getBackground( )Color getForeground( )

Here is a very simple applet that sets the background color to cyan, the foreground color to red, and displays a message that illustrates the order in which the init( ), start( ), and paint( ) methods are called when an applet starts up:

/* A simple applet that sets the foreground and background colors and outputs a string. */import java.awt.*;import java.applet.*;/*<applet code="Sample" width=300 height=50></applet>*/public class Sample extends Applet{

String msg;// set the foreground and background colors.public void init()

Page 33: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

{setBackground(Color.cyan);setForeground(Color.red);msg = "Inside init( ) --";

}// Initialize the string to be displayed.public void start() {

msg += " Inside start( ) --";}// Display msg in applet window.public void paint(Graphics g) {

msg += " Inside paint( ).";g.drawString(msg, 10, 30);

}}

The methods stop( ) and destroy( ) are not overridden, because they are not needed by this simple applet.

Requesting RepaintingAs a general rule, an applet writes to its window only when its update( ) or paint( ) method is called by the AWT. This raises an interesting question: How can the applet itself cause its window to be updated when its information changes? For example, if an applet is displaying a moving banner, what mechanism does the applet use to update the window each time this banner scrolls? Remember, one of the fundamental architectural constraints imposed on an applet is that it must quickly return control to the AWT run-time system. It cannot create a loop inside paint( ) that repeatedly scrolls the banner, for example. This would prevent control from passing back to the AWT.Given this constraint, it may seem that output to our applet’s window will be difficult at best. Fortunately, this is not the case. Whenever our applet needs to update the information displayed in its window, it simply calls repaint( ).The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a call to our applet’s update( ) method, which, in its default implementation, calls paint( ). Thus, for another part of our applet to output to its window, simply store the output and then call repaint( ). The AWT will then execute a call to paint( ), which can display the stored information. For example, if part of our applet needs to output a string, it can store this string in a String variable and then call repaint( ). Inside paint( ), we will output the string using drawString( ).The repaint( ) method has four forms. Let’s look at each one, in turn. The simplest version of repaint( ) is shown here:

void repaint( )

This version causes the entire window to be repainted. The following version specifies a region that will be repainted:

void repaint(int left, int top, int width, int height)THE JAVA LIBRARY

Page 34: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

Here, the coordinates of the upper-left corner of the region are specified by left and top, and the width and height of the region are passed in width and height. These dimensions are specified in pixels. We save time by specifying a region to repaint.Window updates are costly in terms of time. If we need to update only a small portion of the window, it is more efficient to repaint only that region.Calling repaint( ) is essentially a request that our applet be repainted sometime soon. However, if our system is slow or busy, update( ) might not be called immediately. Multiple requests for repainting that occur within a short time can becollapsed by the AWT in a manner such that update( ) is only called sporadically. Thiscan be a problem in many situations, including animation, in which a consistent updatetime is necessary. One solution to this problem is to use the following forms of repaint( ):

void repaint(long maxDelay)void repaint(long maxDelay, int x, int y, int width, int height)

Here, maxDelay specifies the maximum number of milliseconds that can elapse before update( ) is called. Beware, though. If the time elapses before update( ) can be called, it isn’t called. There’s no return value or exception thrown, so we must be careful.It is possible for a method other than paint( ) or update( ) to output to an applet’s window. To do so, it must obtain a graphics context by calling getGraphics( ) (defined by Component) and then use this context to output to the window. However, for mostapplications, it is better and easier to route window output through paint( ) and to callrepaint( ) when the contents of the window change.A Simple Banner AppletTo demonstrate repaint( ), a simple banner applet is developed. This applet scrollsa message, from right to left, across the applet’s window. Since the scrolling of themessage is a repetitive task, it is performed by a separate thread, created by the appletwhen it is initialized. The banner applet is shown here:/* A simple banner applet.This applet creates a thread that scrollsthe message contained in msg right to leftacross the applet's window.*/import java.awt.*;import java.applet.*;/*<applet code="SimpleBanner" width=300 height=50></applet>*/public class SimpleBanner extends Applet implements Runnable {String msg = " A Simple Moving Banner.";Thread t = null;int state;boolean stopFlag;// Set colors and initialize thread.public void init() {setBackground(Color.cyan);setForeground(Color.red);}// Start thread

Page 35: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

public void start() {t = new Thread(this);stopFlag = false;t.start();}// Entry point for the thread that runs the banner.public void run() {char ch;// Display bannerfor( ; ; ) {try {repaint();Thread.sleep(250);ch = msg.charAt(0);msg = msg.substring(1, msg.length());msg += ch;if(stopFlag)break;} catch(InterruptedException e) {}}}// Pause the banner.public void stop() {stopFlag = true;t = null;}// Display the banner.public void paint(Graphics g) {g.drawString(msg, 50, 30);}}Following is sample output:Let’s take a close look at how this applet operates. First, notice that SimpleBannerextends Applet, as expected, but it also implements Runnable. This is necessary, sincethe applet will be creating a second thread of execution that will be used to scroll thebanner. Inside init( ), the foreground and background colors of the applet are set.After initialization, the AWT run-time system calls start( ) to start the applet running.Inside start( ), a new thread of execution is created and assigned to the Thread variablet. Then, the boolean variable stopFlag, which controls the execution of the applet, is setto false. Next, the thread is started by a call to t.start( ). Remember that t.start( ) calls amethod defined by Thread, which causes run( ) to begin executing. It does not causea call to the version of start( ) defined by Applet. These are two separate methods.Inside run( ), the characters in the string contained in msg are repeatedly rotated left.Between each rotation, a call to repaint( ) is made. This eventually causes the paint( )method to be called and the current contents of msg is displayed. Between eachiteration, run( ) sleeps for a quarter of a second. The net effect of run( ) is that thecontents of msg is scrolled right to left in a constantly moving display. The stopFlagvariable is checked on each iteration. When it is true, the run( ) method terminates.If a browser is displaying the applet when a new page is viewed, the stop( ) method iscalled, which sets stopFlag to true, causing run( ) to terminate. This is the mechanism used

Page 36: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

to stop the thread when its page is no longer in view. When the applet is brought back intoview, start( ) is once again called, which starts a new thread to execute the banner.

Using the Status WindowIn addition to displaying information in its window, an applet can also output amessage to the status window of the browser or applet viewer on which it is running.To do so, call showStatus( ) with the string that we want displayed. The status windowis a good place to give the user feedback about what is occurring in the applet, suggestoptions, or possibly report some types of errors. The status window also makes anexcellent debugging aid, because it gives we an easy way to output information aboutour applet.The following applet demonstrates showStatus( ):// Using the Status Window.import java.awt.*;import java.applet.*;/*<applet code="StatusWindow" width=300 height=50></applet>*/public class StatusWindow extends Applet{public void init() {setBackground(Color.cyan);}// Display msg in applet window.public void paint(Graphics g) {g.drawString("This is in the applet window.", 10, 20);showStatus("This is shown in the status window.");}}Sample output from this program is shown here:

Page 37: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

Event Handling

Applets are event-driven programs. Thus, event handling is at the core of successful applet programming. Most events to which our applet will respond are generated by the user. These events are passed to our applet in a variety of ways, with the specific method depending upon the actual event. There are several types of events. The most commonly handled events are those generated by the mouse, the keyboard, and various controls, such as a push button. Events are supported by the java.awt.event package.

The Delegation Event ModelThe modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once received, the listener processes the event and then returns. The advantage of this design is that the application logic that processes events is cleanly separated from the user interface logic that generates those events. A user interface element is able to “delegate” the processing of an event to a separate piece of code.In the delegation event model, listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them.

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

Event SourcesA source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event.A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. Here is the general form:

public void addTypeListener(TypeListener el)

Here, Type is the name of the event and el is a reference to the event listener. For example, the method that registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse motion listener is called addMouseMotionListener( ). When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent only to listeners that register to receive them.Some sources may allow only one listener to register. The general form of such a method is this:

Page 38: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

public void addTypeListener(TypeListener el) throws java.util.TooManyListenersExceptionTHE JAVA LIBRARYHere, Type is the name of the event and el is a reference to the event listener. When such an event occurs, the registered listener is notified. This is known as unicasting the event.A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general form of such a method is this:

public void removeTypeListener(TypeListener el)

Here, Type is the name of the event and el is a reference to the event listener. For example, to remove a keyboard listener, we would call removeKeyListener( ).The methods that add or remove listeners are provided by the source that generates events. For example, the Component class provides methods to add and remove keyboard and mouse event listeners.

Event ListenersA listener is an object that is notified when an event occurs. It has two major requirements.

1. It must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.2. The methods that receive and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved. Any object may receive and process one or both of these events if it provides an implementation of this interface.

Event ClassesThe classes that represent events provide a consistent, easy-to-use means of encapsulating events.At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events. Its one constructor is shown here:

EventObject(Object src)

Here, src is the object that generates this event. EventObject contains two methods: getSource( ) and toString( ). The getSource( ) method returns the source of the event. Its general form is shown here:

Object getSource( )

The toString( ) method returns the string equivalent of the event. The class AWTEvent, defined within the java.awt package, is a subclass of EventObject. It is the superclass of all AWT-based events used by the delegation event model. Its getID( ) method can be used to determine the type of the event. The signature of this method is shown here:

int getID( )

To summarize: EventObject is a superclass of all events.

Page 39: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

AWTEvent is a superclass of all AWT events that are handled by the delegation event model.

The package java.awt.event defines several types of events that are generated by various user interface elements.

Event Class DescriptionActionEvent Generated when a button is pressed, a list item is double-

clicked, or a menu item is selected.AdjustmentEvent Generated when a scroll bar is manipulated.ComponentEvent Generated when a component is hidden, moved, resized, or

becomes visible.ContainerEvent Generated when a component is added to or removed from

a container.FocusEvent Generated when a component gains or loses keyboard

focus.InputEvent Abstract super class for all component input event classes.ItemEvent Generated when a check box or list item is clicked; also

occurs when a choice selection is made or a checkable menu item is selected or deselected. JAVA

KeyEvent Generated when input is received from the keyboard.MouseEvent Generated when the mouse is dragged, moved, clicked,

pressed, or released; also generated when the mouse enters or exits a component.

MouseWheelEvent Generated when the mouse wheel is moved. TextEvent Generated when the value of a text area or text field is

changed.WindowEvent Generated when a window is activated, closed, deactivated,

deiconified, iconified, opened, or quit.

The ActionEvent ClassAn ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is selected. The ActionEvent class defines four integer constants that can be used to identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK. In addition, there is an integer constant, ACTION_PERFORMED, which can be used to identify action events.

ActionEvent has these three constructors:

ActionEvent(Object src, int type, String cmd)ActionEvent(Object src, int type, String cmd, int modifiers)ActionEvent(Object src, int type, String cmd, long when, int modifiers)

Here, src is a reference to the object that generated this event. The type of the event is specified by type, and its command string is cmd. The argument modifiers indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. The when parameter specifies when the event occurred. We can obtain the command name for the invoking ActionEvent object by using the getActionCommand( ) method, shown here:

String getActionCommand( )

Page 40: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

For example, when a button is pressed, an action event is generated that has a command name equal to the label on that button.The getModifiers( ) method returns a value that indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. Its form is shown here:

int getModifiers( )

The getWhen( ) method returns the time at which the event took place. This is called the event’s timestamp. The getWhen( ) method is shown here.

long getWhen( )

The KeyEvent ClassA KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated.All key presses do not result in characters. For example, pressing the SHIFT key does not generate a character.There are many other integer constants that are defined by KeyEvent. For example, VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters. Here are some others:

VK_ENTER VK_ESCAPE VK_CANCEL VK_UPVK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWNVK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL

The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or alt.

KeyEvent is a subclass of InputEvent. Here are two of its constructors:

KeyEvent(Component src, int type, long when, int modifiers, int code)KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the key was pressed is passed in when. The modifiers argument indicates which modifiers were pressed when this key event occurred.The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The character equivalent (if one exists) is passed in ch. If no valid character exists, then ch contains CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED.The KeyEvent class defines several methods, but the most commonly used ones are getKeyChar( ), which returns the character that was entered, and getKeyCode( ), which returns the key code. Their general forms are shown here:

char getKeyChar( )int getKeyCode( )

Page 41: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED. When a KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.

The MouseEvent ClassThere are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them:

MOUSE_CLICKED The user clicked the mouse.MOUSE_DRAGGED The user dragged the mouse.MOUSE_ENTERED The mouse entered a component.MOUSE_EXITED The mouse exited from a component.MOUSE_MOVED The mouse moved.MOUSE_PRESSED The mouse was pressed.MOUSE_RELEASED The mouse was released.MOUSE_WHEEL The mouse wheel was moved.

MouseEvent is a subclass of InputEvent. Here is one of its constructors.

MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup)

Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.The most commonly used methods in this class are getX( ) and getY( ). These return the X and Y coordinates of the mouse when the event occurred. Their forms are shown here:

int getX( )int getY( )

Alternatively, we can use the getPoint( ) method to obtain the coordinates of the mouse. It is shown here:

Point getPoint( )

It returns a Point object that contains the X, Y coordinates in its integer members: x and y.The translatePoint( ) method changes the location of the event. Its form is shown here:

void translatePoint(int x, int y)

Here, the arguments x and y are added to the coordinates of the event.

The getClickCount( ) method obtains the number of mouse clicks for this event. Its signature is shown here:

int getClickCount( )

Page 42: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

The isPopupTrigger( ) method tests if this event causes a pop-up menu to appear on this platform. Its form is shown here:

boolean isPopupTrigger( )

The getButton( ) method is shown here.

int getButton( )

It returns a value that represents the button that caused the event. The return value will be one of these constants defined by MouseEvent.

NOBUTTON BUTTON1 BUTTON2 BUTTON3

The NOBUTTON value indicates that no button was pressed or released. LIBRARYSources of EventsHere some of the user interface components that can generate the events described in the previous section. In addition to these graphical user interface elements, other components, such as an applet, can generate events. For example, we receive key and mouse events from an applet.

Event Source DescriptionButton Generates action events when the button is pressed.Checkbox Generates item events when the check box is selected or

deselected.Choice Generates item events when the choice is changed.List Generates action events when an item is double-clicked; generates

item events when an item is selected or deselected.Menu Item Generates action events when a menu item is selected;

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

Scrollbar Generates adjustment events when the scroll bar is manipulated.Text components Generates text events when the user enters a character.Window Generates window events when a window is activated, closed,

deactivated, deiconified, iconified, opened, or quit.

Event Listener InterfacesThe delegation event model has two parts: sources and listeners. Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. When an event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument.

The following sections examine the specific methods that are contained in each interface.

Interface DescriptionActionListener Defines one method to receive action events.AdjustmentListener Defines one method to receive adjustment events.ComponentListener Defines four methods to recognize when a component is hidden,

moved, resized, or shown.

Page 43: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

ContainerListener Defines two methods to recognize when a component is added to or removed from a container.

FocusListener Defines two methods to recognize when a component gains or loses keyboard focus.

ItemListener Defines one method to recognize when the state of an item changes.

KeyListener Defines three methods to recognize when a key is pressed, released, or typed.

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

MouseMotionListener Defines two methods to recognize when the mouse is dragged or moved.

MouseWheelListener Defines one method to recognize when the mouse wheel is moved.

TextListener Defines one method to recognize when a text value changes.WindowFocusListener Defines two methods to recognize when a window gains or

loses input focus.WindowListener Defines seven methods to recognize when a window is activated,

closed, deactivated, deiconified, iconified, opened, or quit.

The ActionListener InterfaceThis interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its general form is shown here:

void actionPerformed(ActionEvent ae)

The KeyListener InterfaceThis interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked when a key is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been entered.For example, if a user presses and releases the A key, three events are generated in sequence: key pressed, typed, and released. If a user presses and releases the HOME key, two key events are generated in sequence: key pressed and released.

The general forms of these methods are shown here:

void keyPressed(KeyEvent ke)void keyReleased(KeyEvent ke)void keyTyped(KeyEvent ke)

The MouseListener InterfaceThis interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is pressed and released, respectively.

The general forms of these methods are shown here:

void mouseClicked(MouseEvent me)void mouseEntered(MouseEvent me)

Page 44: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

void mouseExited(MouseEvent me)void mousePressed(MouseEvent me)void mouseReleased(MouseEvent me)

The MouseMotionListener InterfaceThis interface defines two methods. The mouseDragged( ) method is called multiple times as the mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved. Their general forms are shown here:

void mouseDragged(MouseEvent me)void mouseMoved(MouseEvent me)

Using the Delegation Event ModelApplet programming using the delegation event model is actually quite easy. Just follow these two steps:1. Implement the appropriate interface in the listener so that it will receive the type of event desired.2. Implement code to register and unregister (if necessary) the listener as a recipient for the event notifications.Remember that a source may generate several types of events. Each event must be registered separately. Also, an object may register to receive several types of events, but it must implement all of the interfaces that are required to receive these events.

Handling Mouse EventsTo handle mouse events, we must implement the MouseListener and the MouseMotionListener interfaces. The following applet demonstrates the process. It displays the current coordinates of the mouse in the applet’s status window. Each time a button is pressed, the word “Down” is displayed at the location of the mouse pointer. Each time the button is released, the word “Up” is shown. If a button is clicked, the message “Mouse clicked” is displayed in the upper-left corner of the applet display area.As the mouse enters or exits the applet window, a message is displayed in the upper-left corner of the applet display area. When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is dragged. Notice that the two variables, mouseX and mouseY, store the location of the mouse when a mouse pressed, released, or dragged event occurs. These coordinates are then used by paint( ) to display output at the point of these occurrences.

// Demonstrate the mouse event handlers.import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code="MouseEvents" width=300 height=100></applet>*/THE JAVA LIBRARYpublic class MouseEvents extends Applet implements MouseListener, MouseMotionListener {

String msg = "";int mouseX = 0, mouseY = 0; // coordinates of mousepublic void init()

Page 45: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

{addMouseListener(this);addMouseMotionListener(this);

}// Handle mouse clicked.public void mouseClicked(MouseEvent me) {

// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse clicked.";repaint();

}// Handle mouse entered.public void mouseEntered(MouseEvent me) {

// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse entered.";repaint();

}// Handle mouse exited.public void mouseExited(MouseEvent me) {

// save coordinatesmouseX = 0;mouseY = 10;msg = "Mouse exited.";repaint();

}// Handle button pressed.public void mousePressed(MouseEvent me) {

// save coordinatesmouseX = me.getX();mouseY = me.getY();msg = "Down";repaint();

}// Handle button released.public void mouseReleased(MouseEvent me) {

// save coordinatesmouseX = me.getX();mouseY = me.getY();msg = "Up";repaint();

}// Handle mouse dragged.public void mouseDragged(MouseEvent me)

Page 46: Exception-Handling€¦  · Web viewThe Java Thread Model. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading

{// save coordinatesmouseX = me.getX();mouseY = me.getY();msg = "*";showStatus("Dragging mouse at " + mouseX + ", " + mouseY);repaint();

}// Handle mouse moved.public void mouseMoved(MouseEvent me) {

// show statusshowStatus("Moving mouse at " + me.getX() + ", " + me.getY());

}// Display msg in applet window at current X,Y location.public void paint(Graphics g) {

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

}