Você está na página 1de 48

UNIT III APPLET CLASS

Applet Basics Simple Applet HTML applet Tag Event Handling Event Classes Event Listeners Adapter Classes

APPLET BASICS
INTRODUCTION

An applet, as the name implies, is a kind of mini-application, designed to be run by a Web browser, or in the context of some other "applet viewer." Applets differ from regular applications in a number of ways.

Java applets are actually compiled Java class files that are run on a page within a Web browser. Because the Web browser supplies the framework for retrieving and loading an applet and also supplies the main window holding the applet, Java applets are somewhat simpler than a true Java application.

Java applets, meanwhile, can be loaded from anywhere on the Internet, and therefore are subject to severe security restrictions. First exposure to Java was in the form of a Java applet running within a Web page. Java applets currently are being used for advertising purposes because they provide the capability to include simple animation and sound in a Web advertisement.

DIFFERENCES BETWEEN JAVA APPLETS AND JAVA APPLICATIONS


Java applications are standalone Java programs that can be run by using just the Java interpreter, for example, from a command line. Most everything you've used up to this point in the book has been a Java application, albeit a simple one. Java applets, however, are run from inside a World Wide Web browser. A reference to an applet is embedded in a Web page using a special HTML tag. When a reader, using a Java-enabled browser, loads a Web page with an applet in it, the browser downloads that applet from a Web server and executes it on the local system (the one the browser is running on). (The Java interpreter is built into the browser and runs the compiled Java class file from there.)

Java applets run inside a Java browser, they have access to the structure the browser provides: an existing window, an event-handling and graphics context , and the surrounding user interface . Java applications can also create this structure (allowing you to create graphical applications), but they don't require it.

One final significant difference between Java applets and applications-probably the biggest difference-is the set of restrictions placed on how applets can operate in the name of security. Java applets can be downloaded from any site on the World Wide Web and run on a client's system, Java-enabled browsers and tools limit what can be done to prevent a rogue applet from causing system damage or security breaches. Without these restrictions in place, Java applets could be written to contain viruses or trojan horses (programs that seem friendly but do some sort of damage to the system), or be used to compromise the security of the system that runs them. Restrictions on Applets 1. Applets can't read or write to the reader's file system, which means they cannot delete files or test to see what programs you have installed on the hard drive. 2. Applets can't communicate with any network server other than the one that had originally stored the applet, to prevent the applet from attacking another system from the reader's system. 3. Applets can't run any programs on the reader's system. For UNIX systems, this includes forking a process. 4. Applets can't load programs native to the local platform, including shared libraries such as DLLs.

Java applications have none of these restrictions.

NOTE
1. The security restrictions imposed on applets are sometimes called "the sandbox". Work is being done by Sun and by the Java community to find ways for applets to be able to break out of the sandbox, including digital signatures and encryption. 2. In addition to the applet restrictions listed, Java itself includes various forms of security and consistency checking in the Java compiler and interpreter for all Java programs to prevent unorthodox use of the language.

APPLET PACKAGE
Every applet is implemented by creating a subclass of the Applet class. The following figure shows the inheritance hierarchy of the Applet class.

Inheritance Hierarchy of Applet Class The Applet Package contains a number of methods that are designed to be used in the construction of applets and in the special circumstances that arise with applets. Example: Applets need to be able to load images and audio clips from a server, so the methods getImage() and getAudioClip() are part of the Applet Package.

The Applet Package contains a number of useful methods.

A SUMMARY OF METHODS IN THE APPLET PACKAGE.

Method
public String getAppletInfo() public URL getDocumentBase() public String getParameter(String name) public String [][] getParameterInfo()

Function
Returns information about the applet, such as author Returns the URL of the HTML document Returns the parameters for an applet Returns a summary of what the parameters control Used to load an image file Used to play a previously loaded audio clip Lets you know whether an applet is active Used to resize the applet Displays a status string in the applet's browser Initializes the applet Starts the applet when it's finished initializing Stops the applet when you leave the applet's page Destroys the applet when you leave the browser

public AudioClip getAudioClip(URL) Used to load an audio clip public Image getImage(URL) public void play(URL) public boolean isActive() public void resize(int, int) public void showStatus(String msg) public void init() public void start() public void stop() public void destroy()

CREATING APPLETS
All the Java applications are programs with a single main() method that create objects, set instance variables, and run methods. To create an applet, you have to create a subclass of the class Applet. The Applet class, part of the java.applet package, provides much of the behavior your applet needs to work inside a Java-enabled browser. Applets also take strong advantage of Java's Abstract Windowing Toolkit (awt), which provides behavior for creating graphical user interface (GUI)-based applets and applications like: Drawing to the screen. Creating windows, menu bars, buttons, check boxes, and other UI elements. Managing user input such as mouse clicks and keypresses. The awt classes are part of the java.awt package. Java's Abstract Windowing Toolkit (awt) provides classes and behavior for creating GUI-based applications in Java. Applets make use of many of the capabilities in the awt.The Initial applet class always has a signature like this: public class myClass extends java.applet.Applet { ..... } Note the public keyword. Java requires that your applet subclass be declared public.

APPLET METHODS
When a Java-enabled browser encounters your applet in a Web page, it loads your initial applet class over the network, as well as any other helper classes that first class uses, and runs the applet using the browser's built-in bytecode interpreter. Unlike with applications, where Java calls the main() method directly on your initial class, when your applet is loaded, Java creates an instance of the applet class, and a series of special applet methods are called on that instance. Different applets that use the same class use different instances, so each one can behave differently from the other applets running in the same browser. Applets are built using an application framework. You inherit from class Applet and override the appropriate methods. These methods are: METHOD init( ) start( ) OPERATION Called when the applet is first created to perform firsttime initialization of the applet Called every time the applet moves into sight on the Web browser to allow the applet to start up its normal operations (especially those that are shut off by stop( )). Also called after init( ). Part of the base class Component (three levels of inheritance up). Called as part of an update( ) to perform special painting on the canvas of an applet. Called every time the applet moves out of sight on the Web browser to allow the applet to shut off expensive operations. Also called right before destroy( ). Called when the applet is being unloaded from the page to perform final release of resources when the applet is no longer used

paint( )

stop( )

destroy( )

Consider the paint( ) method. This method is called automatically when the Component (in this case, the applet) decides that it needs to update itself perhaps because its being moved back onto the screen or placed on the screen

for the first time, or perhaps some other window had been temporarily placed over your Web browser. The applet calls its update( ) method (defined in the base class Component), which goes about restoring everything, and as a part of that restoration calls paint( ). When update( ) calls paint( ) it hands it a handle to a Graphics object that represents the surface on which you can paint. This is important because youre limited to the surface of that particular component and thus cannot paint outside that area. In the case of an applet, the surface is the area inside the applet. The Graphics object also has a set of operations you can perform on it. These operations revolve around painting on the canvas, so most of them have to do with drawing images, shapes, arcs, etc.The most commonly used one is drawString( ). For this, you must specify the String you want to draw and its starting location on the applets drawing surface. This location is given in pixels.

LIFE CYCLE OF AN APPLET


(MAJOR APPLET ACTIVITIES) To create a basic Java application, your class has to have one method, main(), with a specific signature. Then, when your application runs, main() is found and executed, and from main() you can set up the behavior that your program needs to run. Applets are similar but more complicated-and, in fact, applets don't need a main() method at all. Applets have many different activities that correspond to various major events in the life cycle of the applet-for example, initialization, painting, and mouse events. Each activity has a corresponding method, so when an event occurs, the browser or other Java-enabled tool calls those specific methods. Default implementations of these activity methods do nothing; to provide behavior for an event you must override the appropriate method in your applet's subclass. You don't have to override all the methods. Different applet behavior requires different methods to be overridden.

Five important methods in an applet's execution: initialization, starting, stopping, destroying, and painting.

INITIALIZATION Initialization occurs when the applet is first loaded (or reloaded), similarly to the main() method in applications. The initialization of an applet might include reading and parsing any parameters to the applet, creating any helper objects it needs, setting up an initial state, or loading images or fonts. To provide behavior for the initialization of your applet, override the init() method in your applet class:

public void init() { ... }

STARTING After an applet is initialized, it is started. Starting is different from initialization because it can happen many different times during an applet's lifetime, whereas initialization happens only once. Starting can also occur if the applet was previously stopped. For example, an applet is stopped if the reader follows a link to a different page, and it is started again when the reader returns to this page. To provide startup behavior for your applet, override the start() method:

public void start() { ... }

Functionality given in the start() method might include creating and starting up a thread to control the applet, sending the appropriate messages to helper objects, or in some way telling the applet to begin running STOPPING Stopping and starting go hand in hand. Stopping occurs when the reader leaves the page that contains a currently running applet, or you can stop the applet yourself by calling stop(). By default, when the reader leaves a page, any threads the applet had started will continue running. By overriding stop(), you can suspend execution of these threads and then restart them if the applet is viewed again:

public void stop() { ... } DESTROYING Destroying sounds more violent than it is. Destroying enables the applet to clean up after itself just before it is freed or the browser exits-for example, to stop and remove any running threads, close any open network connections, or release any

other running objects. Generally, you won't want to override destroy() unless you have specific resources that need to be released-for example, threads that the applet has created. To provide clean-up behavior for your applet, override the destroy() method:

public void destroy() { ... } PAINTING Painting is how an applet actually draws something on the screen, be it text, a line, a colored background, or an image. Painting can occur many thousands of times during an applet's life cycle (for example, after the applet is initialized, if the browser is placed behind another window on the screen and then brought forward again, if the browser window is moved to a different position on the screen, or perhaps repeatedly, in the case of animation). You override the paint() method if your applet needs to have an actual appearance on the screen (that is, most of the time). The paint() method looks like this:

public void paint(Graphics g) { ... }

Note that unlike the other major methods in this section, paint() takes an argument, an instance of the class Graphics. It has to be made sure that the Graphics class (part of the java.awt package) gets imported into your applet code, usually through an import statement at the top of your Java file: import java.awt.Graphics;

APPLET EXAMPLES
EXAMPLE 1 - A First Applet
The simplest possible applet you can write in Java. This example introduces the paint() method, which is invoked by the applet viewer (or Web browser) when the applet needs to be drawn. This method should perform graphical output--such as drawing text or lines or displaying images--for your applet. The argument to paint() is a Graphics object that you use to do the drawing.

CODING import java.applet.*; import java.awt.*; // Compulsory Import Statements // in any applet

/* <APPLET code="FirstApplet.class" width=150 height=100> </APPLET> */ public class FirstApplet extends Applet { // This method displays the applet. // The Graphics class is used to do all drawing in Java. public void paint(Graphics g) { g.drawString("Hello World", 25, 50); } }

OUTPUT

Viewing Applets
Applets are displayed as a part of a Web page by using the HTML tag <APPLET>. To run an applet, you need a Web browser or some other software that serves the function of a browser, such as the applet viewer program that ships with the Java Development Kit from JavaSoft. The browser acts as the operating system for the applet--you cannot run an applet as a standalone program in the same way you can run an executable file. The two leading browsers--Netscape Navigator (version 2.02 and later) and Microsoft Internet Explorer (version 3.0 and later)--both support Java applets. A third choice--Sun's HotJava--also handles applets but is not widely used. These programs load applets from a Web page and run them remotely on the Web user's computer. This arrangement raises security issues that must be handled by the Java language itself and by Java-enabled browsers.

EXAMPLE 2 - A Simple Applet


import java.awt.Graphics; import java.awt.Font; import java.awt.Color; public class HelloAgainApplet extends java.applet.Applet { Font f = new Font("TimesRoman", Font.BOLD, 36); public void paint(Graphics g) { g.setFont(f); g.setColor(Color.red); g.drawString("Hello again!", 5, 40); } } Analysis This applet implements the paint() method, one of the major methods (actually, it overrides the default implementation of paint(), which does nothing). Because the applet doesn't actually do much (all it does is print a couple words to the screen), and there's not really anything to initialize, you don't need a start(), stop(), init(), or destroy() method.

The paint method is where the real work of this applet (what little work goes on) really occurs. The Graphics object passed into the paint() method holds the graphics state for the applet-that is, the current features of the drawing surface, such as foreground and background colors or clipping area.

It also set up the font and color for this graphics state (here, the font object held in the f instance variable, and a Color object representing the color red).

HTML APPLET TAG


THE <APPLET> TAG
Syntax : The syntax for using the <APPLET> tag is the following:
<APPLET attributes> applet_parameters alternate_content </APPLET>

The APPLET attributes are standard values that all applets accept and are a standard part of HTML. The applet_parameters are applet-specific parameters that are read by the applet at runtime. This is a handy way of passing arguments to an applet to allow the applet to be more generic.

<APPLET> TAG ATTRIBUTES


1. ALT -Alternate text that can be displayed by text-only browsers.

2. ALIGN-The ALIGN attribute designates the alignment of the applet within the browser page. 3. CODE-(Required) The CODE attribute is used to indicate the .class file that loads the applet. 4. CODEBASE-The CODEBASE attribute is used to indicate the location of the .class file that loads the applet. 5. HEIGHT-(Required) The HEIGHT attribute is used to set the applet's bounding rectangle height. 6. HSPACE-The HSPACE attribute sets the amount of horizontal space to set off around the applet. 7. NAME-The NAME attribute sets the symbolic name of the applet. 8. VSPACE-The VSPACE attribute sets the amount of vertical space to set off around the applet. 9. WIDTH-(Required) The WIDTH attribute is used to set the applet's box width.

MORE ABOUT THE <APPLET> TAG


In its simplest form, by using CODE, WIDTH, and HEIGHT, the <APPLET> tag merely creates a space of the appropriate size and then loads and runs the applet in that space. The <APPLET> tag, however, does include several attributes that can help you better integrate your applet into the overall design of your Web page. Note The attributes available for the <APPLET> tag are almost identical to those for the HTML <IMG> tag. ALIGN

The ALIGN attribute defines how the applet will be aligned on the page. This attribute can have one of nine values: LEFT, RIGHT, TOP, TEXTTOP, MIDDLE, ABSMIDDLE, BASELINE, BOTTOM, or ABSBOTTOM.

In the case of ALIGN=LEFT and ALIGN=RIGHT, the applet is placed at the left or right margin of the page, respectively, and all text following that applet flows in the space to the right or left of that applet. The text will continue to flow in that space until the end of the applet, or you can use a line break tag (<BR>) with the CLEAR attribute to start the left line of text below that applet. The CLEAR attribute can have one of three values: CLEAR=LEFT starts the text at the next clear left margin, CLEAR=RIGHT does the same for the right margin, and CLEAR=ALL starts the text at the next line where both margins are clear.

NOTE
In Netscape Navigator for Windows, the use of the ALIGN attribute prevents the applet from actually being loaded (this is a bug; it works fine in the UNIX and Macintosh versions of Netscape, as well as in Internet Explorer). If you're using alignment extensively in your Web pages with applets, you might want to enclose them in tables and align the tables themselves rather than use ALIGN. Example Here's a snippet of HTML code that aligns an applet against the left margin, has some text flowing alongside it, and then breaks at the end of the paragraph so that the next bit of text starts below the applet:

CODING <P> <APPLET CODE="HelloAgainApplet.class" WIDTH=200 HEIGHT=50 ALIGN=LEFT>Hello Again!</APPLET> To the left of this paragraph is an applet. It's a simple, unassuming applet, in which a small string is printed in red type, set in 36 point Times bold. <BR CLEAR=ALL>

<P>In the next part of the page, we demonstrate how under certain conditions, styrofoam peanuts can be used as a healthy snack.

The following figure shows how this applet and the text surrounding it might appear in a Java-enabled browser

An applet aligned left. For smaller applets, you might want to include your applet within a single line of text. To do this, there are seven values for ALIGN that determine how the applet is vertically aligned with the text:

ALIGN=TEXTTOP aligns the top of the applet with the top of the tallest text in the line. ALIGN=TOP aligns the applet with the topmost item in the line (which may be another applet, or an image, or the top of the text). ALIGN=ABSMIDDLE aligns the middle of the applet with the middle of the largest item in the line. ALIGN=MIDDLE aligns the middle of the applet with the middle of the baseline of the text. ALIGN=BASELINE aligns the bottom of the applet with the baseline of the text. ALIGN=BASELINE is the same as ALIGN=BOTTOM, but ALIGN=BASELINE is a more descriptive name. ALIGN=ABSBOTTOM aligns the bottom of the applet with the lowest item in the line (which may be the baseline of the text or another applet or image).

The following figure shows the various alignment options, where the line is an image and the arrow is a small applet.

Applet alignment options.

HSPACE AND VSPACE

The HSPACE and VSPACE attributes are used to set the amount of space, in pixels, between an applet and its surrounding text. HSPACE controls the horizontal space (the space to the left and right of the applet). VSPACE controls the vertical space (the space above and below).

Example Here's that sample snippet of HTML with vertical space of 50 and horizontal space of 10:

CODING <P> <APPLET CODE="HelloAgainApplet.class" WIDTH=300 HEIGHT=200 ALIGN=LEFT VSPACE=50 HSPACE=10>Hello Again!</APPLET> To the left of this paragraph is an applet. Its a simple, unassuming applet, in which a small string is printed in red type, set in 36 point Times bold. <BR CLEAR=ALL> <P>In the next part of the page, we demonstrate how under certain conditions, styrofoam peanuts can be used as a healthy snack.

OUTPUT

Vertical and horizontal space.

CODE and CODEBASE The final two attributes to note in <APPLET> are CODE and CODEBASE. Unlike the other attributes, neither of these has anything to do with the applet's appearance on the page; these two refer to the actual location of the Java applet file so that the Java-enabled browser can find it. CODE is used to indicate the name of the class file that holds the current applet. If CODE is used alone in the <APPLET> tag, the class file is searched for in the same directory as the HTML file that references it. Note that class filenames used in CODE have the .class extension; this is different from in the Java command-line interpreter, which doesn't use the extension. If you want to store your class files in a different directory on your Web server than that of your HTML files, you have to tell the browser where to find those class files. To do this, you use CODEBASE. CODE contains only the name of the class file; CODEBASE contains an alternate pathname (actually a URL or relative pathname) where classes are contained. Example If you store your class files in a directory called classes, which are in the same directory as your HTML files, CODEBASE is the following: <APPLET CODE="myclass.class" CODEBASE="classes" WIDTH=100 HEIGHT=100></APPLET> If you store all your Java classes in some central location, you can also use a URL in CODEBASE: <APPLET CODE="myclass.class" CODEBASE="http://myserver.com/javaclasses" WIDTH=100 HEIGHT=100></APPLET>

If class files are actually stored on an entirely different server altogether, You can use that URL in CODEBASE as well: <APPLET CODE="myclass.class" CODEBASE="http://www.joesserver.com/javaclasses" WIDTH=100 HEIGHT=100></APPLET>

PASSING PARAMETERS TO JAVA APPLETS


Parameters are an easy way to configure Java applets without actually changing the source file. CODING : MoreHelloApplet class.
1: import java.awt.Graphics; 2: import java.awt.Font; 3: import java.awt.Color; 4: 5: public class MoreHelloApplet extends java.applet.Applet { 6: 7: Font f = new Font("TimesRoman", Font.BOLD, 36); 8: String name; 9: 10: public void init() { 11: name = getParameter("name"); 12: if (name == null) 13: name = "Laura"; 14: 15: name = "Hello " + name + "!"; 16: } 17: 18: public void paint(Graphics g) { 19: g.setFont(f); 20: g.setColor(Color.red); 21: g.drawString(name, 5, 40); 22: } 23: }

Create the HTML file that contains this applet. The following coding shows a new Web page for the MoreHelloApplet applet.

The HTML file for the MoreHelloApplet applet.


1: <HTML> 2: <HEAD> 3: <TITLE>Hello!</TITLE> 4: </HEAD> 5: <BODY> 6: <P> 7: <APPLET CODE="MoreHelloApplet.class" WIDTH=200 HEIGHT=50> 8: <PARAM NAME=name VALUE="Bonzo"> 9: Hello to whoever you are! 10: </APPLET> 11: </BODY> 12: </HTML>

Analysis Note the <APPLET> tag, which points to the class file for the applet and has the appropriate width and height (200 and 50). Just below it (line 8) is the <PARAM> tag, which you use to pass in the value for the name. Here, the NAME parameter is simply name, and the VALUE is the string "Bonzo". OUTPUT

The Java applet determine the value of the parametersby calling the getParameter() method supplied by the java.applet.Applet parent class.

Here are three methods commonly used by applets:


String getParameter(String name)-Returns

the value for the specified

parameter string
URL getCodeBase()-Returns URL

the URL of the applet the URL of the document containing the

getDocumentBase()-Returns

applet

EVENT HANDLING
INTRODUCTION
Most programs, to be useful, must respond to commands from the user. To do so, Java programs rely on events that describe user actions. Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All it has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source. Components can generate many kinds of events.

JAVA EVENT HANDLING MODEL


GUIs are event driven Generate events when user interacts with GUI

Mouse movements, mouse clicks, typing in a text field, etc. Event information stored in object that extends AWTEvent

To process an event Register an event listener

Object from a class that implements an event-listener interface (from java.awt.event ) "Listens" for events Implement event handler

Method that is called in response to an event Event handling interface has one or more methods that must be defined Delegation event model Use of event listeners in event handling Processing of event delegated to particular object

When an event occurs GUI component notifies its listeners

Calls listener's event handling method.

Example Enter pressed in a TextField Method actionPerformed called for registered listener

Each event is represented by an object that gives information about the event and identifies the event source. Event sources are typically components, but other kinds of objects can also be event sources. As the following figure shows, each event source can have multiple listeners registered on it. Conversely, a single listener can register with multiple event sources.

Multiple listeners can register to be notified of events of a particular type from a particular source. In this model, different classes of events are represented by different Java classes. Every event is a subclass of java.util.EventObject. AWT events, which is what we are concerned with here, are subclasses of

java.awt.AWTEvent. The various types of AWT events, such as MouseEvent and ActionEvent, are placed in the new java.awt.event package. Every event has a source object, which can be obtained with getSource(), and every AWT event has a type value, which can be obtained with getID(). This value is used to distinguish the various types of events that are represented by the same event class. For example, the FocusEvent and has two possible types: Event

FocusEvent.FOCUS_GAINED

FocusEvent.FOCUS_LOST.

subclasses contain whatever data values are pertinent to the particular event type.

For example, MouseEvent has getX(), getY(), and getClickCount() methods; it also inherits the getModifiers() and getWhen() methods, among others. The event handling model is based on the concept of an "event listener." An object interested in receiving events is an event listener. An object that generates events (an event source) maintains a list of listeners that are interested in being notified when events occur, and provides methods that allow listeners to add themselves and remove themselves from this list of interested objects. When the event source object generates an event (or when a user input event occurs on the event source object), the event source notifies all the listener objects that the event has occurred.

An event source notifies an event listener object by invoking a method on it and passing it an event object (an instance of a subclass of EventObject). In order for a source to invoke a method on a listener, all listeners must implement the required method.

It ensured that all event listeners for a particular type of event implement a corresponding interface. For example, event listener objects for ActionEvent events must implement the ActionListener interface. The java.awt.event package defines an event listener interface for each of the event types it defines. (Actually, for MouseEvent events, it defines two listener interfaces: MouseListener and MouseMotionListener.) All event listener interfaces themselves extend java.util.EventListener. This interface does not define any methods, but instead acts as a marker interface, clearly identifying all event listeners as such.

An event

listener interface may define more than one method.

For example, an event class like MouseEvent represents several different types of mouse events, such as a button press event and a button release event, and these different event types cause different methods in the corresponding event listener to be invoked. By convention, the methods of an event listener are passed a single argument, which is an event object of the type that

corresponds to the listener. This event object should contain all the information a program needs to respond to the event

HOW TO IMPLEMENT AN EVENT HANDLER ? Every event handler requires three bits of code: 1. In the declaration for the event handler class, code that specifies that the class either implements a listener interface or extends a class that implements a listener interface. For example: public class MyClass implements ActionListener {

2. Code that registers an instance of the event handler class as a listener upon one or more components. For example: someComponent.addActionListener(instanceOfMyClass);

3. Code that implements the methods in the listener interface. For example: public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }

EVENTS
When the user interacts with a GUI application, an event is generated. Examples of user events are clicking a button, selecting an item or closing a window. Events are represented as Objects in JavaTM technology. The super class of all event classes is java.util.EventObject. Some of the important classes and their hierarchy is shown below.

EVENT CLASS HIERARCHY


The top most super class of all the new event classes is java.util.EventObject

The Event Class Hierarchy

IMPORTANT METHODS Object getSource(); One sub class of EventObject is java.awt.AWTEvent, which is the super class of all the delegation model event classes. Again there is only one method of interest: int getID(); which returns ID of the event. An events id is an int that specifies the exact nature of the event.

The hierarchy is as follows:

Java.util.EventObject Java.awt.AWTEvent
o o o

ActionEvent AdjustmentEvent ComponentEvent


ContainerEvent FocusEvent InputEvent


KeyEvent MouseEvent

o o

PaintEvent WindowEvent

ItemEvent TextEvent

The InputEvent super class has a long getWhen() method that returns the time when the event took place. AWT EVENT CLASSES

The subclasses of AWT Event can be categorized into two groups: Semantic events : Semantic events directly correspond to high level user interactions with a GUI component. Clicking of a button is an example of a semantic event. Following event classes are semantic classes. 1. ActionEvent 2. AdjustmentEvent 3. ItemEvent

4. TextEvent Low-level events: Multiple low-level events may get generated for each high level user event. Following event classes are low level event classes. 1. ComponentEvent 2. ContainerEvent 3. FocusEvent 4. KeyEvent 5. MouseEvent 6. PaintEvent 7. WindowEvent

EVENT CLASSES FOR GUI CONTROLS


By GUI component I mean objects like Button, ListBox etc. For each Java GUI component a set of events of above type are generated. It is important to understand which events are generated for each component.

Event types and corresponding EventSource & EventListener

Event Type ActionEvent

Event Source Button, List, MenuItem, TextField

Event Listener interface ActionListener AdjustmentListener ItemListener TextListener ComponentListener ContainerListener

AdjustmentEvent Scrollbar ItemEvent TextEvent Choice, Checkbox, CheckboxMenuItem, List TextArea, TextField

ComponentEvent Component ContainerEvent Container

FocusEvent KeyEvent MouseEvent WindowEvent

Component Component Component Window

FocusListener KeyListener MouseListener, MouseMotionListener WindowListener

EVENT LISTENERS
An event listener is an object to which a component has delegated the task of handling a particular kind of event. When the component experiences input, an event of the appropriate type is constructed and passed as the parameter to a method call on the listener. A listener must implement the interface that contains the event handling method. These are objects that define methods to handle certain type of events. An event source (for example a PushButton) can generate one or more type of events, and maintain a list of event listeners for each type of event. An event source can register listeners by calling addXListener type of methods. For example a Button may register an object for handling ActionEvent by calling addActionListener. This object would then need to implement the listener interface corresponding to ActionEvent, which is ActionListener The standard formula for giving an action listener to a component is:

1. Create a listener class that implements the appropriate interface. 2. Construct the component. 3. Construct an instance of listener class. 4. Call addTypeListener() on the component, passing in the listener object.

A component may have multiple listeners for any event type. There is no guarantee that listeners will be notified in the order in which they were added. There is also no guarantee that all listener notification will occur in the same thread; thus listeners must take precautions against corrupting shared data.

An event listener may be removed from a components list of listeners by calling a removeXXXListener() method, passing in the listener to be removed.

LISTENER INTERFACES AND THEIR METHODS


ActionListener

ActionPerformed (ActionEvent)

AdjustmentListener

AdjustmentValueChanged (AdjustmentEvent)

ComponentListener 1. ComponentHidden (ComponentEvent) 2. ComponentMoved (ComponentEvent) 3. ComponentResized (ComponentEvent) 4. ComponentShown (ComponentEvent) ContainerListener 1. ComponentAdded (ContainerEvent) 2. ComponentRemoved (ContainerEvent) FocusListener 1. FocusGained (FocusEvent) 2. FocusLost (FocusEvent) ItemListener

ItemStateChanged (ItemEvent)

KeyListener 1. KeyPressed (KeyEvent) 2. KeyReleased (KeyEvent) 3. KeyTyped (KeyEvent)

MouseListener 1. MousePressed (MouseEvent) 2. MouseReleased (MouseEvent) 3. MouseClicked (MouseEvent) 4. MouseEntered (MouseEvent) 5. MouseExited (MouseEvent) MouseMotionListener 1. MouseMoved (MouseMotionListener) 2. MouseDragged (MouseMotionListener) TextListener

textValueChanged (TextEvent)

WindowListener 1. windowActivated (WindowEvent) 2. windowClosed (WindowEvent) 3. windowClosing (WindowEvent) 4. windowDeactivated (WindowEvent) 5. windowDeiconified (WindowEvent) 6. windowIconified (WindowEvent) 7. windowOpened (WindowEvent)

CODING // A window with just an OK button. public class exampleWindow extends Frame { Button OkButton; OkHandler handler; public exampleWindow() { //Constructor /* Code to create a window, button and set a layout Manager. */ /* Now create and add listener */ handler = new OkHandler(this); OkButton.addActionListener(handler); } public static void main (String args []) { new exampleWindow(); } } /* Now define a listener object. It must implement the interface ActionListener by defining the function actionPerformed. */ class OkHandler implements ActionListener { private exampleWindow win; public OkHandler(exampleWindow window) { win=window; } public void actionPerformed(ActionEvent evt) { // Process clicking of button here. } }

So to set up the processing of events the following tasks must be done. I. For the GUI component (like pushbutton) associate a listener object class with the component by calling a method of type addXListener (See table below for list of methods). II. Define this listener object. It must implement the corresponding interface. The name of interface is of type EventListener. Table below gives list of event listeners. III. The object must define all the methods defined in the interface it is implementing. See table for the list of Event Listener methods defined in each Event Listener interface. Event Listener Interfaces and corresponding methods which it defines Event Listener interface ActionListener AdjustmentListener ItemListener TextListener Event Listener Methods actionPerformed(ActionEvent evt) adjustmentValueChanged(AjustmentEvent evt) itemStateChanged(ItemEvent evt) textValueChanged(TextEvent evt) componentHidden(ComponentEvent evt), ComponentListener componentMoved(ComponentEvent evt), componentResized(ComponentEvent evt), componentShown(ComponentEvent evt) ContainerListener FocusListener KeyListener componentAdded(ContainerEvent evt), componentRemoved(ContainerEvent evt) focusGained(FocusEvent evt), focusLost(FocusEvent evt) keyPressed(KeyEvent evt), keyReleased(KeyEvent evt), keyTyped(KeyEvent evt) mouseClicked(MouseEvent evt), MouseListener mouseEntered(MouseEvent evt), mouseExited(MouseEvent evt),

mousePressed(MouseEvent evt), mouseReleased(MouseEvent evt) MouseMotionListener mouseDragged(MouseEvent evt), mouseMoved(MouseEvent evt) windowActivated(WindowEvent evt), windowClosed(WindowEvent evt), windowClosing(WindowEvent evt), WindowListener windowDeactivated(WindowEvent evt), windowDeiconified(WindowEvent evt), windowIconified(WindowEvent evt), windowOpened(WindowEvent evt)

ADAPTER CLASSES
Event adapters facilitate implementing listener interfaces. Many event listener interfaces have more than one event listener methods. For such interfaces, Java technology defines adapter classes. These have empty implementation (stubs) of all the event listener methods defined in the interface they implement. A listener can subclass the adapter and override only stub methods for handling events of interest. The table below lists the low level event listener interfaces and their adapters.

Event Listener Interfaces and their corresponding adapter classes. Event Listener interface Event Listener Adapter ComponentListener ContainerListener ComponentAdapter ContainerAdapter

FocusListener KeyListener MouseListener MouseMotionListener WindowListener

FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter

EXAMPLE OF ADAPTER CLASSES


CODING

import java.awt.*; import java.awt.event.*; public class MouseBeeper extends MouseAdapter {

public void mouseClicked(MouseEvent e) { Toolkit.getDefaultToolkit().beep(); } }

Without extending the MouseAdapter class, I would have had to write the same class like this import java.awt.*; import java.awt.event.*;

public class MouseBeeper implements MouseListener {

public void mouseClicked(MouseEvent e) { Toolkit.getDefaultToolkit().beep();

public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {}

EXAMPLE PROGRAMS HANDLING MOUSE AND KEY BOARD EVENTS.

MOUSE EVENTS
Responding to mouse input is a simple matter. Because responding to the events generated by the mouse are such an important and common task in modern programming, Javas classes already includes special methods for responding to these events. A mouse generates six types of event messages that you can capture in your applets. These events are listed below, along with their descriptions and the method that handles them:

MOUSE_DOWN-This event, which is handled by the mouseDown() method, is caused when the user presses the mouse button.

MOUSE_UP-This event, which is handled by the mouseUp() method, is caused when the user releases the left mouse button.

MOUSE_MOVE-This event, which is handled by the mouseMove() method, occurs when the user moves the mouse pointer on the screen.

MOUSE_DRAG-This event, which is handled by the mouseDrag() method, is generated when the user moves the mouse pointer while holding down the left mouse button.

MOUSE_ENTER-This event, which is handled by the mouseEnter() method, is sent when the mouse pointer enters the area owned by an applet or component.

MOUSE_EXIT-This event, which is handled by the mouseExit() method, occurs when the mouse pointer leaves the area owned by an applet or a component.

HANDLING MOUSE CLICKS The most commonly used mouse event in Java programs (and any other program written for a graphical user interface) is the MOUSE_DOWN event, which is generated whenever the user clicks within an applet. It's the MOUSE_DOWN event, for example, that lets Java know when an on-screen button component has been clicked. You don't have to worry about clicks on on-screen buttons (usually), because they're handled by Java. Java provides a couple of methods by which you can respond to mouse events. The easiest way to capture a MOUSE_DOWN event is to override the applet's mouseDown() method. Java automatically calls mouseDown() whenever the MOUSE_DOWN event is generated, which makes responding to this event easier than melting butter with a blowtorch. The mouseDown() method's signature looks like this: public boolean mouseDown(Event evt, int x, int y) The arguments passed to the function are an Event object and the X,Y coordinates of the mouse event. Although Java has already extracted the X,Y mouse coordinates for you, you can also get them from the Event object by examining the values stored in the x and y data fields, as described in Table 25.1. (Because Java has already extracted the

coordinates for you, though, it makes more sense to use the x and y parameters sent to the function.) NOTE Although most of Java's event-handling methods automatically receive as arguments the basic information you need about a specific event (such as the coordinates of a mouse click), you can extract whatever additional information you need from the Event object, which is always the first parameter in a message-handling method.

EXAMPLE -- Using Mouse Clicks in an Applet As I was describing the mouseDown() method in the previous section, I felt an example coming on. And, sure enough, here it is. The applet in Listing 25.1 responds to mouse clicks by printing the word "Click!" wherever the user clicks in the applet. It does this by storing the coordinates of the mouse click in the applet's coordX and coordY data fields. The paint() method then uses these coordinates to display the word.

CODING : MouseApplet.java: Using Mouse Clicks in an Applet. import java.awt.*; import java.applet.*; public class MouseApplet extends Applet { int coordX, coordY; public void init() { coordX = -1;

coordY = -1; Font font = new Font("TimesRoman", Font.BOLD, 24); setFont(font); resize(400, 300); } public void paint(Graphics g) { if (coordX != -1) g.drawString("Click!", coordX, coordY); } public boolean mouseDown(Event evt, int x, int y) { coordX = x; coordY = y; repaint(); return true; } }

EXPLANATION ( of above given Java Program) Tell Java that the applet uses the classes in the awt package. Tell Java that the applet uses the classes in the applet package. Derive the MouseApplet class from Java's Applet class. Declare the class's data fields. Override the init() method. Initialize the click coordinates. Create and set the font for the applet. Size the applet. Override the paint() method.

If the user has selected a coordinate... Draw the word Click! at the selected coordinate. Override the mouseDown() method. Save the mouse click's coordinates. Force Java to repaint the applet. Tell Java that the event was handled. NOTE When you run MouseApplet, you'll discover that the applet window gets erased each time the paint() method is called. That's why only one "Click!" ever appears in the window.

HANDLING MOUSE MOVEMENT


Although mouse clicks are the most common type of mouse event to which your applet may want to respond, tracking the mouse pointer's movement can also be useful. Drawing programs, for example, enable you to draw shapes by tracking the movement of the mouse and displaying the results on the screen. Unlike mouse clicks, though, which are rare, only occurring when the user presses a mouse button, MOUSE_MOVE events come flooding into your applet by the hundreds as the user moves the mouse around the screen. Each one of these events can be handled in the mouseMove() method, whose signature looks like this: public boolean mouseMove(Event evt, int x, int y) Aguments an Event object and the X,Y coordinates at which the event occurred. EXAMPLE -- Responding to Mouse Movement in an Applet Responding to mouse movement isn't something you have to do often in your applets.

For example, when need to track mouse movement when writing a game applet that uses the mouse as input. A more common use is in graphics programs that enable you to draw on the screen. Listing 25.2 is just such an applet. Click the mouse in the window to choose a starting point and then move the mouse around the window. Wherever the mouse pointer goes, it leaves a black line behind

CODING -- MouseApplet2.java: An Applet That Tracks Mouse Movement.


import java.awt.*; import java.applet.*; public class MouseApplet2 extends Applet { Point startPoint; Point points[]; int numPoints; boolean drawing; public void init() { startPoint = new Point(0, 0); points = new Point[1000]; numPoints = 0; drawing = false; resize(400, 300); } public void paint(Graphics g) { int oldX = startPoint.x; int oldY = startPoint.y; for (int x=0; x<numPoints; ++x) {

g.drawLine(oldX, oldY, points[x].x, points[x].y); oldX = points[x].x; oldY = points[x].y; } } public boolean mouseDown(Event evt, int x, int y) { drawing = true; startPoint.x = x; startPoint.y = y; return true; } public boolean mouseMove(Event evt, int x, int y) { if ((drawing) && (numPoints < 1000)) { points[numPoints] = new Point(x, y); ++numPoints; repaint(); } return true; } }

EXPLANATION ( of above given Java Program)

Tell Java that the applet uses the classes in the awt package. Tell Java that the applet uses the classes in the applet package. Derive the MouseApplet2 class from Java's Applet class. Declare the class's data fields. Override the init() method. Initialize the starting point. Create an array for storing the coordinates of line segments. Create and set the font for the applet.

Set point count to zero. Set drawing flag off. Size the applet. Override the paint() method. Initialize the drawing's starting point. Cycle through each element in the points[] array. Draw a line segment. Save ending point as the starting point for the next line. Override the mouseDown() method. Set the flag in order to allow drawing to begin. Save the mouse click's coordinates. Tell Java that the event was handled. Override the mouseMove() method. if it's okay to add another line segment... Create a new point and save the mouse's coordinates. Increment the point counter. Force Java to repaint the applet. Tell Java that the event was handled.

KEYBOARD EVENTS

Obviously there may be times when you'll want to handle the keyboard events at a lower level than you can with something like a TextField control. Java responds to two basic key events, which are represented by the KEY_PRESS and KEY_RELEASE constants. Java defines methods that make it just as easy to respond to the keyboard as it is to respond to the mouse.

RESPONDING TO KEY PRESSES


Whenever the user presses a key when an applet is active, Java sends the applet a KEY_PRESS event. In your applet, you can respond to this event by overriding the keyDown() method, whose signature looks like this: public boolean keyDown(Event evt, int key) This method receives two arguments, which are an Event object and an integer representing the key that was pressed. This integer is actually the ASCII representation of the character represented by the key. In order to use this value in your programs, however, you must first cast it to a char value, like this: char c = (char)key;

EXAMPLE -- Using Key Presses in an Applet


Although capturing key presses is a fairly simple process, there's nothing like an example applet to put the theoretical stuff to the test. It is an applet called KeyApplet that displays whatever key the user presses. NOTE If you run KeyApplet under a browser like Netscape Navigator, click on the applet with your mouse before you start typing. This ensures that the applet has the focus and will receive the key presses.

CODING -- KeyApplet.java: An Applet That Captures Key Presses.


import java.awt.*; import java.applet.*; public class KeyApplet extends Applet { int keyPressed; public void init() { keyPressed = -1; Font font =new Font("TimesRoman", Font.BOLD, 144); setFont(font); resize(200, 200); } public void paint(Graphics g) { String str = ""; if (keyPressed != -1) { str += (char)keyPressed; g.drawString(str, 40, 150); } } public boolean keyDown(Event evt, int key) { keyPressed = key; repaint(); return true; } }

EXPLANATION ( of above given Java Program)

Tell Java that the applet uses the classes in the awt package. Tell Java that the applet uses the classes in the applet package. Derive the KeyApplet class from Java's Applet class. Declare the class's data field. Override the init() method. Initialize keyPressed to indicate no valid key received yet. Create and set the font for the applet. Size the applet. Override the paint() method. Create the empty display string. Draw the character on the screen. Override the keyDown() method. Save the key that was pressed. Force Java to redraw the applet. Tell Java that the event was handled.

Você também pode gostar