a pplet applets are small applications that are accessed on an internet server, transported over the...

43
APPLET 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 Every applet that you create must be a subclass of Applet. applet begins with two import statements. 1. import java.applet.*; 2. import java.awt.*; (Active Window Toolkit)

Upload: loraine-boyd

Post on 19-Jan-2018

215 views

Category:

Documents


0 download

DESCRIPTION

Method Description Image getImage(URL url) Returns an Image object that encapsulates the image found at the location specified by url. Image getImage(URL url,String imageName) Returns an Image object that encapsulates the image found at the location specified by url and having the name specified by imageName. Locale getLocale( ) Returns a Locale object that is used by various locale-sensitive classes and methods. String getParameter(String paramName) Returns the parameter associated with paramName. null is returned if the specified parameter is not found. String[ ] [ ] getParameterInfo( ) Returns a String table that describes the parameters recognized by the applet. Each entry in the table must consist of three strings that contain the name of the parameter, a description of its type and/or range, and an explanation of its purpose. void init( ) Called when an applet begins execution. It is the first method called for any applet. boolean isActive( ) Returns true if the applet has been started. It returns false if the applet has been stopped. static final AudioClip newAudioClip(URL url) Returns an AudioClip object that encapsulates the audio clip found at the location specified by url. This method is similar to getAudioClip( ) except that it is static and can be executed without the need for an Applet object.

TRANSCRIPT

Page 1: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

APPLET 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

Every applet that you create must be a subclass of Applet.

applet begins with two import statements.

1. import java.applet.*; 2. import java.awt.*; (Active Window Toolkit)

Page 2: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

APPLET CLASS The Applet class defines the methods shown in following

tableMethod Description

void destroy( ) Called by the browser just before an applet isterminated. Your applet will override this method if it needs to perform any cleanup prior to its destruction.

AccessibleContextgetAccessibleContext( ) Returns the accessibilty context for the invoking

object.

AppletContext getAppletContext( ) Returns the context associated with the applet.

String getAppletInfo( ) Returns a string that describes the applet.

AudioClip getAudioClip(URL url) Returns an AudioClip object that encapsulates the audio clip found at the location specified by url.

AudioClip getAudioClip(URL url,String clipName) Returns an AudioClip object that encapsulates the audio clip found at the location specified by url and having the name specified by clipName.

URL getCodeBase( ) Returns the URL associated with the invoking applet.

URL getDocumentBase( ) Returns the URL of the HTML document that invokes the applet.

Page 3: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Method Description

Image getImage(URL url) Returns an Image object that encapsulates the image found at the location specified by url.

Image getImage(URL url,String imageName) Returns an Image object that encapsulates the image found at the location specified by url and having the name specified by imageName.

Locale getLocale( ) Returns a Locale object that is used by various locale-sensitive classes and methods.

String getParameter(String paramName) Returns the parameter associated with paramName. null is returned if the specified parameter is not found.

String[ ] [ ] getParameterInfo( ) Returns a String table that describes the parametersrecognized by the applet. Each entry in the table must consist of three strings that contain the name of the parameter, a description of its type and/or range, and an explanation of its purpose.

void init( ) Called when an applet begins execution. It is the first method called for any applet.

boolean isActive( ) Returns true if the applet has beenstarted. It returns false if the applet hasbeen stopped.

static final AudioClipnewAudioClip(URL url) Returns an AudioClip object that encapsulates the

audio clip found at the location specified by url. This method is similar to getAudioClip( ) except that it is static and can be executed without the need for an Applet object.

Page 4: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Method Description

void play(URL url) If an audio clip is found at the location specified by url, the clip is played.

void play(URL url, String clipName) If an audio clip is found at the location specified by url with the name specified by clipName, the clip is played.

void resize(Dimension dim) Resizes the applet according to the dimensions specified by dim. Dimension is a class stored inside java.awt. It contains two integer fields:

width and height.

void resize(int width, int height) Resizes the applet according to the dimensions specified by width and height.

final void setStub(AppletStub stubObj) Makes stubObj the stub for the applet. This method is used by the run-time system and is not usually called by your applet. A stub is a small piece of code that provides the linkage betweenyour applet and the browser.

void showStatus(String str) Displays str in the status window of the browser or applet viewer. If the browser does not support a status window, then no action takes place.

void start( ) Called by the browser when an applet should start (or resume) execution. It is automatically called after init( ) when an applet first begins. void stop( ) Called by the browser to suspendexecution of the applet. Once stopped, an applet is restarted when the browser calls start( ).

void stop( ) Called by the browser to suspend execution of the applet. Once stopped, an applet is restarted when the browser calls start( ).

Page 5: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

EXAMPLE DESCRIBING USE OF FIVE METHODS

// An Applet skeleton.import java.awt.*;import java.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 6: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

OUTPUT WILL BE THE BLANK APPLET

HTML document

<HTML> <BODY> <APPLET code = “Appletskel.class” width = 200 height = 60> </APPLET> </BODY></HTML>

Page 7: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

1. init( ):The init( ) method is the first method to be called. This is where you

shouldinitialize variables. This method is called only once during the run

time of yourapplet.

Syntax : public void init()

2. 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( ).

Syntax : public void start()

Page 8: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

3. paint( ):The paint( ) method is called each time your applet’s output must be redrawn. 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 inwhich the applet is running. This context is used whenever output to the applet is required.

Syntax: public void paint(Graphics g)

4. stop( ):

The stop( ) method is called when a web browser leaves the HTML documentContaining the applet—when it goes to another page, for example. When

stop( ) is called, the applet is probably running. You should use stop( ) to suspend threads that don’t need to run when the applet is not visible. You can restart them when start( ) is called if the user returns to the page.

Syntax : public void stop()

Page 9: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

5. destroy( ):The destroy( ) method is called when the environment

determines thatyour applet needs to be removed completely from memory. At

thispoint, you should free up any resources the applet may be

using. The stop( ) method is always called before destroy( ).

Syntax: public void destroy()

Page 10: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

THE HTML APPLET TAG

The APPLET tag is used to start an applet from both an HTML document and from an applet viewer.

An applet viewer will execute each APPLET tag that it finds in a separate window

web browsers like Netscape Navigator, Internet Explorer, and HotJava will allow many applets on a single page.

Page 11: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

The standard APPLET tag is shown here. Bracketed items

are optional.

< APPLET[CODEBASE = codebaseURL]CODE = appletFile[ALT = alternateText][NAME = appletInstanceName]WIDTH = pixels HEIGHT = pixels[ALIGN = alignment][VSPACE = pixels] [HSPACE = pixels]

>[< PARAM NAME = AttributeName VALUE =AttributeValue>][< PARAM NAME = AttributeName2 VALUE = AttributeValue>]. . .[HTML Displayed in the absence of Java]

</APPLET>

Page 12: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

CODEBASE:

1. specifies the base URL of the applet code, which is the directory that will be searched for the applet’s executable class file (specified by the CODE tag).2. The HTML document’s URL directory is used as the CODEBASE if this attribute is not specified.

CODE:

1. CODE is a required attribute that gives the name of the file containing your applet’s compiled .class file. ALT:

1. ALT used to specify a short text message that should be displayed if the browser understands the APPLET tag but can’t currently run Java applets. NAME:

1. Used to specify a name for the applet instance.2. Applets must be named in order for other applets on the same page to find them by name and communicate with them. 3. To obtain an applet by name, use getApplet( ), which is defined by the AppletContext interface.

Page 13: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

WIDTH AND HEIGHT:

1. WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area. ALIGN:

1. ALIGN specifies the alignment of the applet.2. with these possible values:LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.

VSPACE AND HSPACE:

1. VSPACE specifies the space,in pixels, above and below the applet. 2. HSPACE specifies the space, in pixels, on each side of the applet.

PARAM NAME AND VALUE:

1. The PARAM tag allows you to specify applet specific arguments in an HTML page. Applets access their attributes with the getParameter( ) method.

Page 14: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

SIMPLE APPLET DISPLAY METHODS

Line

g.drawLine(35, 45, 75, 95);drawLine(int x1, int y1, int x2, int y2)

Used to draw a straight line from point (x1,y1) to (x2,y2).

Rectangle

 

g.drawRect(35, 45, 25, 35);drawRect(int x, int y, int width, int length)

Used to draw a rectangle with the upper left corner at (x,y) and with the specified width and length.

Round Edge

Rectangle

g.drawRoundRect(35,45,25,35,10,10);drawRoundRect(int x, int y, int width, int           length, int arcWidth, int arcHeight) Used to draw a rounded edged rectangle.  The amount of rounding is controlled by arcWidth and arcHeight.

Page 15: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Oval / Circle

 

g.drawOval(25, 35, 25, 35);g.drawOval(25, 35, 25, 25); → circle

drawOval(int x, int y, int width, int length)

Used to draw an oval inside an imaginary rectangle whose upper left corner is at (x,y).  To draw a circle keep the width and length the same.

Arc

g.drawArc(35, 45, 75, 95, 0, 90);drawArc(int x, int y, int width, int length,                       int startAngle, int arcAngle)

Used to draw an arc inside an imaginary rectangle whose upper left corner is at (x,y).  The arc is drawn from the startAngle to startAngle + arcAngle and is measured in degrees.       A startAngle of 0º points horizontally to the right (like the unit circle in math).  Positive is a counterclockwise rotation starting at 0º.

Page 16: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Polygon

int [ ] x = {20, 35, 50, 65, 80, 95};int [ ] y = {60, 105, 105, 110, 95, 95};g.drawPolygon(x, y, 6);drawPolygon(int x[ ], int y[ ], int n) Used to draw a polygon created by n line segments.  The command will close the polygon.  (x-coordinates go in one array with accompanying y-coordinates in the other)

String(text)

g.drawString("Java is cool!", 40, 70);drawString(String str, int x, int y); Draws a string starting at the point indicated by (x,y).  Be sure you leave enough room from the top of the screen for the size of the font.

Page 17: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

FILLING GRAPHICS WITH COLOR

Fill an Arcg.fillArc(35, 45, 75, 95, 0, 90);

Draws and fills an arc with a previously set color.

Fill an Ovalg.fillOval(35, 45, 75, 95);

Draws and fills an oval with a previously set color.

Fill a Rectangle

g.fillRect(35, 45, 75, 95);Draws and fills a rectangle with a previously set color.

Page 18: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Fill a Round Rectangle

 

g.fillRoundRect(2,2,25,35,20,20); Draws and fills with a previously set color.

Fill a Polygon

 

int [ ] x = {20, 20, 30, 50, 30, 20};int [ ] y = {10, 25, 35, 40, 35, 30};g.fillPolygon(x, y, 6); Draws and fills a polygon with a previously set color.

Page 19: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

These commands will draw the figure and fill the space with color. 

g.setColor(Color.orange);g.fillRect(35,45,75,95);                

EDGE:  If you want a distinct "edge" around the figure, also draw the figure in a contrasting color after the fill command. 

g.setColor(Color.orange);g.fillRect(35,45,75,95);g.setColor(Color.black);g.drawRect(35, 45, 75, 95);

Page 20: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

TEXT PROPERTIES Not only can you print text messages in a graphic display, you can

also control the font, style and size of the printed text. Fonts:

We will be controlling the font name, the font style (PLAIN, BOLD, ITALIC), and the font size.  Check out these examples:

Font timesBold16 = new Font("Times New Roman", Font.BOLD, 16);Font arialBolditalic12 = new Font("Arial", Font.BOLD + Font.ITALIC, 12);

The names of the fonts will depend upon the computer running the program.  There is Java code that will tell you which font names are available on your computer.

String [ ] MyFontNames = Toolkit.getDefaultToolkit( ) . getFontList( );for (int x = 0; x < MyFontNames.length; x++)    System.out.println(MyFontNames[x]); 

Sample coding using Font class:Font

courierBold10 = new Font("Courier", Font.BOLD, 10);g.setColor(Color.red);g.setFont(courierBold10);g.drawString("Java Rules!!!", 120, 120);

Page 21: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

BACKGROUND & FOREGROUND COLORING

1. To set the background color of an applet’s window, use setBackground( ). 2. 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 shownhere that can be used to specify colors:Color.blackColor.magenta Color.blue Color.orange Color.cyan Color.pink Color.darkGray Color.red Color.gray Color.white Color.green Color.yellowColor.lightGray

For example, this sets the background color to green and the text color to red:setBackground(Color.green);setForeground(Color.red);

Page 22: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

REPAINT( ):The repaint( ) method is defined by the AWT. It causes the AWT run-timesystem to execute a call to your applet’s update( ) method, which, in its default implementation, calls paint( ). Thus, for another part of your 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.

Forms of repaint:

void repaint()void repaint(int left, int top, int width, int height)

Page 23: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

AWT CLASSESThe AWT classes are contained in the java.awt package.

Class Description

1. AWTEvent Encapsulates AWT events.2. AWTEventMulticaster Dispatches events to multiple

listeners.3. BorderLayout The border layout manager.

Border layouts use five components: North, South, East, West, and Center.

4. Button Creates a push button control.5. Canvas A blank, semantics-free window.6. CardLayout The card layout manager. Card layouts

emulateindex cards. Only the one on top is

showing.7. Checkbox Creates a check box control.8. CheckboxGroup Creates a group of check box controls.9. CheckboxMenuItem Creates an on/off menu item.10. Choice Creates a pop-up list.11. Color Manages colors in a portable, platform-

independent fashion.

Page 24: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Class Description

12. Component An abstract superclass for various AWT components.13. Container A subclass of Component that can hold other components.14. Cursor Encapsulates a bitmapped cursor.15. Dialog Creates a dialog window.16. Dimension Specifies the dimensions of an object. The width is stored in width, and the height is stored in height.17. Event Encapsulates events.18. EventQueue Queues events.19. FileDialog Creates a window from which a file can be selected.20. FlowLayout The flow layout manager. Flow layout positions components left to right, top to bottom.21. Font Encapsulates a type font.22. FontMetrics Encapsulates various information related to a font. This information helps you display text in a window.23. Frame Creates a standard window that has a title bar, resize corners, and a menu bar.

Page 25: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Class Description

24. Graphics Encapsulates the graphics context. This context is used by the various output methods to display output in a window.25. GraphicsDevice Describes a graphics device such as a screen or printer.26. GraphicsEnvironment Describes the collection of available Font and

GraphicsDevice objects.27. GridBagConstraints Defines various constraints relating to the

GridBagLayout class.28. GridBagLayout The grid bag layout manager. Grid bag layout

displays components subject to the constraints

specified by GridBagConstraints.29. GridLayout The grid layout manager. Grid layout displays

components in a two-dimensional grid.30. Image Encapsulates graphical images.31. Insets Encapsulates the borders of a container.32. Label Creates a label that displays a string.33. List Creates a list from which the user can choose. Similar to the standard Windows list box.34. MediaTracker Manages media objects.35. Menu Creates a pull-down menu.

Page 26: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Class Description

36. MenuBar Creates a menu bar.37. MenuComponent An abstract class implemented by various menu classes.38. MenuItem Creates a menu item.39. MenuShortcut Encapsulates a keyboard shortcut for a menu item.40. Panel The simplest concrete subclass of Container.41. Point Encapsulates a Cartesian coordinate pair, stored in x and y.42. Polygon Encapsulates a polygon.43. PopupMenu Encapsulates a pop-up menu.44. PrintJob An abstract class that represents a print job.45. Rectangle Encapsulates a rectangle.46. Robot Supports automated testing of AWT- based applications. (Added by Java 2, vl.3) 47. Scrollbar Creates a scroll bar control.48. ScrollPane A container that provides horizontal and/or vertical scroll bars for another component.49. SystemColor Contains the colors of GUI widgets such as windows, scroll bars, text, and others.

Page 27: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Class Description

50. TextArea Creates a multiline edit control.51. TextComponent A superclass for TextArea and TextField.

TextField Creates a single-line edit control.

52. Toolkit Abstract class implemented by the AWT.53. Window Creates a window with no frame, no

menu bar, and no title.

Page 28: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Window FundamentalsThe AWT defines windows according to a class hierarchy that adds functionality and specificity with each level.Component:

a) At the top of the AWT hierarchy is the Component class. b) Component is an abstract class that encapsulates all of the

attributes of a visual component.c) All user interface elements that are displayed on the screen and

that interact with the user are subclasses of Component. d) It defines over a hundred public methods that are responsible for

managing events, such as:example: 1) mouse and keyboard input,

2)positioning and sizing the window, and repainting.

e) A Component object is responsible for remembering the current foreground

and background colors and the currently selected text font.

Page 29: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

CLASS HIERARCHY FOR FRAME & PANEL

Component

Container

Window Panel

Frame

Page 30: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

1.Container:► The Container class is a subclass of Component. It has

additional methods that allow other Component objects to be nested

within it. ► A container is responsible for laying out (that is, positioning)

any components that it contains.2. Panel:► The Panel class is a concrete subclass of Container. ► It doesn’t add any new methods; it simply implements

Container. ► A Panel may be thought of as a recursively nestable,

concrete screen component. ► Panel is the superclass for Applet. (When screen output is

directed to an applet, it is drawn on the surface of a Panel object).

► Other components can be added to a Panel object by its add( ) method

(inherited from Container). ► Once these components have been added, you can

position and resize them manually using the setLocation( ), setSize( ), or

setBounds( ) methods defined by Component.

Page 31: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

3. Window:► The Window class creates a top-level window. ► A top-level window is not contained within any other object; it sits directly on the desktop. ► Generally, you won’t create Window objects directly. Instead, you will use a subclass of Window called Frame.

4. Frame:

► Frame encapsulates what is commonly thought of as a “window.” ► It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. ► If you create a Frame object from within an applet, it will contain a warning message, such as “Java Applet Window,” to the user that an applet window has been created. (This message warns users that the window they see was started by an applet and not by software running on their computer.)

Page 32: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

5. Canvas:► Although it is not part of the hierarchy for applet or frame windows, there is one other type of window that you will find valuable: Canvas. ► Canvas encapsulates a blank window upon which you can draw.

Page 33: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

→ Event handling is at the core of successful applet programming.→ Events are supported by the java.awt.event package.

Event Handling

Delegation Event Model:

a)The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. b)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. c)Once receives an event , the listener processes the event and then returns. d)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. e)A user interface element is able to “delegate” the processing of an event to a separate piece of code.f)In the delegation event model, listeners must register with a source in order to receive an event notification.

Page 34: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

☻Eventsa)In the delegation model, an event is an object that describes a state change in a source.b)It can be generated as a consequence of a person interacting with the elements in a graphical user interface. c)Some of the activities that cause events to be generated are 1.pressing a button2.entering a character via the keyboard3.selecting an item in a list4.clicking the moused)Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated,1.when a timer expires2.a counter exceeds a value3. a software or hardware failure occurs4.an operation is completed.

Page 35: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

☻Event Sources:

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

Syntax - public void addTypeListener(TypeListener el)

e)Here, Type is the name of the event and el is a reference to the event listener. f)When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event.

Page 36: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

g) Some sources may allow only one listener to register. The general form of such

a method is this:

Syntax: public void addTypeListener(TypeListener el)throws java.util.TooManyListenersException

Here, 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.

h) A source must also provide a method that allows a listener to unregister an interest in a specific type of event.

i) The general form of such a method is this:

Syntax: 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, you would call removeKeyListener( ).

j) The Component class provides methods to add and remove keyboard and mouse event listeners.

Page 37: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

☻Event Listeners:a)A listener is an object that is notified when an event occurs. b)It has two major requirements.1. It must have been registered with one or more sources to receive

notifications about specific types of events. 2. It must implement methods to receive and process these notifications.c)The methods that receive and process events are defined in a set of interfaces found in java.awt.event.

Page 38: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Event Classes:• The classes that represent events are at the core of Java’s

event handling mechanism.• At the root of the Java event class hierarchy is EventObject,

which is in java.util. • It is the superclass for all events. • EventObject contains two methods: getSource( ) and

toString( ). 1. The getSource( ) method returns the source of the event. Its

general form is shown here:Syntax : Object getSource( )

2. As expected, toString( ) returns the string equivalent of the event.

• The AWTEvent class, defined within the java.awt package, is a subclass of EventObject.

• It is the superclass (either directly or indirectly) 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:

Syntax : int getID( )

Page 39: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Subclasses Of AWTEvent EventObject is a superclass of all events.AWTEvent is a superclass of all AWT events that are handled by the delegation event model.Event Class Description

1.ActionEvent Generated when a button is pressed, a list item is

double-clicked, or a menu item is selected.2.AdjustmentEvent Generated when a scroll bar is manipulated.3.ComponentEvent Generated when a component is hidden, moved, resized, or becomes visible.4.ContainerEvent Generated when a component is added to or

removed from a container.5.FocusEvent Generated when a component gains or loses

keyboard focus.

6.InputEvent Abstract super class for all component input event classes.7.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.

Page 40: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Event Class Description

8.KeyEvent Generated when input is received from the keyboard.9.MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released; also generated when the mouse enters or exits a component.10.MouseWheelEvent Generated when the mouse wheel is

moved. (Added by Java 2, version 1.4)11.TextEvent Generated when the value of a text area or text field is changed.12.WindowEvent Generated when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.

Page 41: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

ActionEvent Class

ActionEvent is generated when1. a button is pressed.2. a list item is double-clicked.3. a menu item is selected.

The ActionEvent class defines four integer constants that

1.ALT_MASK. 2.CTRL_MASK.3. META_MASK. 4. SHIFT_MASK.

In addition, there is an integer constant, ACTION_PERFORMED,

which can be used to identify action events.

Page 42: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

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)

•src is a reference to the object that generates the event. •The type of the event is specified by type. •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.

Page 43: A PPLET applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part

Adjustment Event Class:An AdjustmentEvent is generated by a scroll bar. There are five types of adjustmentevents. The AdjustmentEvent class defines integer constants that can be used to identify them. The constants and their meanings are shown here:

1.BLOCK_DECREMENT The user clicked inside the scroll bar to decrease its value.

2.BLOCK_INCREMENT The user clicked inside the scroll bar to increase its value.

3.TRACK The slider was dragged.

4.UNIT_DECREMENT The button at the end of the scroll bar was clicked to

decrease its value.5.UNIT_INCREMENT The button at the end of the

scroll bar was clicked to increase its value.