APPLETS 1 What is Applets 1 An applet

  • Slides: 145
Download presentation
APPLETS 1

APPLETS 1

What is Applets? 1. An applet is a program written in the Java programming

What is Applets? 1. An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a page. 2. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM). What are the differences between Applets and Application? 1. Applets do not use the main() method for initiating the execution of the code. Applets, when loaded, automatically call certain methods of Applet class to start and execute the applet code. 2. Unlike stand – alone applications, applets cannot be run independently. They are run from inside a Web page using a special feature known as HTML tag. 3. Applets cannot read from or write to the files in the local computer. 4. Applets cannot communicate with other servers on the network. 5. Applets cannot run any program from the local computer. 6. Applets are restricted from using libraries from other languages such as C or C++. (Java language supports this feature through native methods. ) 2

Applet Architecture 1. An applet is a window – based program. 2. First, applets

Applet Architecture 1. An applet is a window – based program. 2. First, applets are event driven. 3. Event – driven architecture impacts the design of an applet. 4. An applet resembles a set of interrupt service routines. 5. An applet waits until an event occurs. 6. The AWT notifies the applet about an event by calling an event handler appropriate action and then quickly return control to the AWT. 7. Second, the user initiates interaction with an applet - not the other way around. 8. As you know, in a non - windowed program, when the program needs input, it will prompt the user and then call some input method, such as read. Line(). 9. This not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when must respond. 10. 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. 11. Applets can contain various controls, such as push buttons and check boxes. 3

Applet Architecture. . 12. When the user interacts with one of these controls, an

Applet Architecture. . 12. When the user interacts with one of these controls, an event is generated. 13. 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. 14. If you have written programs for windows, you know how intimidating that environment can be. 15. Fortunately, Java’s AWT provides a much cleaner approach that is more quickly mastered. 4

An Applet Skeleton or Applet Life Cycle Begin Born (Load Applet) Initialization start( )

An Applet Skeleton or Applet Life Cycle Begin Born (Load Applet) Initialization start( ) stop( ) Running Stopped Idle start( ) Display paint( ) destroy( ) Destroyed Dead End 5 Exit of Browser

An Applet Skeleton or Applet Life Cycle 1. All but the most trivial applets

An Applet Skeleton or Applet Life Cycle 1. All 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. 2. Four of these methods – init( ), start( ), stop( ), and destroy( ) – are defined by Applet. Another, paint(), is defined by the AWT Component class. 3. Default implementations for all of these methods are provided. 4. Applets do no need to override those methods they do not use. 5. However, only very simple applets will not need to define all of them. The applet states is: 1. Born or initialization state 2. Running state 3. Idle state 4. Dead or destroyed state 5. Display state 6

1. Initialization State Applet enters the initialisation state when it is first loaded. This

1. Initialization State Applet enters the initialisation state when it is first loaded. This is achieved by calling the init() method of Applet Class. The applet is born. At this stage, we may do the following, if required, a. Create objects needed by the applet. b. Set up initial values c. Load images or fonts d. set up colors public void init( ) { --------------------------------} Action 7

2. Running State Applets enters the running state when the system call the start

2. Running State Applets enters the running state when the system call the start () method of Applet Class. This occurs automatically after the applet is initailized. Starting can also occur if the applet is already in “stopped” state. For example, we may leave the web page containing the applet temporarily to another page and return back to the page. This again starts the applet running. Note that, unlike init() method, the start() method may be called more than once. We may override the start() method to create a threa to control the applet. public void start( ) { --------------------------------} Action 8

3. Idle or Stopped State An applet becomes idle when it is stopped from

3. Idle or Stopped State An applet becomes idle when it is stopped from running. Stopping occurs automatically when we leave the page containing the currently running applet. We can also do so by calling the stop() method explicitly. If we use a thread to run the applet, then we must use stop() method to terminate thread. We can achieve by overriding the stop( ) method: public void stop( ) { --------------------------------} Action 9

4. Dead State An applet is said to be dead when it is removed

4. Dead State An applet is said to be dead when it is removed from memory. This occurs automatically by invoking the destroy( ) method when we quit the browser. Like initialization, destroying stage occurs only once in the applet’s life cycle. If the applet has created any resources. Like threads we may override the destroy( ) method to clean up these resouces. public void destroy( ) { --------------------------------} Action 10

5. Display State Applet moves to the display state whenever it has to perform

5. Display State Applet moves to the display state whenever it has to perform some output operations on the screen. This happens immediately after the applet enters into the running state. The paint() method is called to accomplish this task. Almost every applet will have a paint() method. Like other methods in the life cycle, the default version of paint() method does absolutely nothing. We must therefore override this method if we want anything to be displayed on the screen. public void paint (Graphics g) { ----------------Display Statements ----------------} 11

The repaint() method has four forms. Void repaint() Void repaint(int left, int top, int

The repaint() method has four forms. Void repaint() Void repaint(int left, int top, int width, int height) Void repaint(long max. Delay, int x, int y, int width, int height) The HTML Applet Tab The APPLET tag is used to start an applet from both an HTML document and from an applet viewer. The syntax for the standard APPLET tag is shown here. Bracketed items are optional. <APPLET [CODEBASE=codebase. UTL] CODE=appletfile [ALT=alternate. Text] [NAME=applet. Instance. Name] WIDTH=pixels HIEGHT=pixels [ALIGN=alignment] [VSPACE=pixels] [HSPACE=pixels]> [<PARAM NAME=Attibute. Name VALUE=Attibute. Value>] [<PARAM NAME=Attibute. Name 2 VALUE=Attibute. Value>]. . . . [HTML Displayed in the absence of Java] </APPLET>

CODE: Code is a required attribute that gives the name of the file containing

CODE: Code is a required attribute that gives the name of the file containing your applet’s compiled. class file. WIDTH and HEIGHT: Width and Height are required attributes that gives the size of the applet display area. PARAM NAME and VALUE : The PARAM tag allows you to specify appletspecific arguments in an HTML page. Applets access their attributes with the get. Parameter() method.

import java. awt. *; import java. applet. *; /* <applet code = "Applet. Demo"

import java. awt. *; import java. applet. *; /* <applet code = "Applet. Demo" width = 300 height = 300> </applet> */ public class Applet. Demo extends Applet { String msg; public void init() { set. Background(Color. cyan); } public void start() { msg += "This is Start method"; } public void stop() { msg += "This is Stop method"; } public void destroy() { msg += "This is Destroy method"; } public void paint(Graphics g) { g. draw. String(msg, 100); } } Specified Colors 1. Color. black 10. Color. pink 2. Color. blue 11. Color. red 3. Color. cyan 12. Color. white 4. Color. dark. Gray 13. Color. yellow 5. Color. gray 6. Color. green 7. Color. light. Gray 8. Color. magenta 9. Color. orange 14

How the applets to be displayed in the Browser <HTML> <HEAD> <TITLE>WELCOME TO c.

How the applets to be displayed in the Browser <HTML> <HEAD> <TITLE>WELCOME TO c. HETTINAD</TITLE> </HEAD> <BODY> <APPLET CODE = Applet. Demo. class WIDTH = 300 HEIGHT = 200 </APPLET> </BODY> </HTML> 15

The HTML APPLET Tag < APPLET [CODEBASE = codebase. URL] CODE = applet. File

The HTML APPLET Tag < APPLET [CODEBASE = codebase. URL] CODE = applet. File [ALT = alternate. Text] [NAME = applet. Instance. Name] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [<PARAM NAME = Attribute. Name VALUE = Attribute. Value>]. . . . [HTML Displayed in the absence of Java] </APPLET> 16

ATTRIBUTE MEANING CODE = Applet. File. Name. class Specifies the name of the applet

ATTRIBUTE MEANING CODE = Applet. File. Name. class Specifies the name of the applet class to be loaded. That is, the name of the already – compiled. class file in which the executable. Java bytecode for the applet is stored. This attribute must be specified. CODEBASE = codebase_URL (Optional) Specifies the URL of the directory in which the applet resides. If the applet resides in the same directory as the HTML file, then the CODEBASE attirbute may be omitted entirely. WIDTH = pixels HEIGHT = pixels These attributes specify the width and height of the space on the HTML page that will be reserved for the applet. NAME=applet_instance_name (Optional) A name for the applet may optionally be specified so that other applets on the page may refer to this applet. This facilitates inter applet communication. ALIGN = alignment (Optional) This optional attribute specifies where on the page the applet will appear. Possible values for alignment are TOP, BOTTOM, LEFT, RIGHT, MIDDLE, ABSBOTTOM, TEXTTOP, AND BASELINE. HSPACE = pixels (Optional) Used only when ALIGN is set to LEFT or RIGHT , this attribute specifies the amount of horizontal blank space the browser should leave surrounding the applet. VSPACE = pixels (Optional) Used only when some vertical alignment is specified with the ALIGN attribute (TOP, BOTTOM, etc. , ) VSPACE specifes the amount of vertical blank space the browser should leave surrounding the applet. ALT = alternate_text (Optional) Non – java browser will display this text where the applet would normally go. This attribute is optional. PARAM NAME AND VALUE The PARAM tag allows you to specify applet – specific arguments 17 in an HTML page. Applets access their attributes with the get. Parameter() method

Passing Parameters to Applets import java. awt. *; import java. applet. *; /* <applet

Passing Parameters to Applets import java. awt. *; import java. applet. *; /* <applet code="Param. Demo" width = 300 height = 300> <param name = font. Name value=Courier> <param name = font. Size value = 30> <param name = leading value=2> <param name = account. Enabled value = true> </applet> */ public class Param. Demo extends Applet { String font. Name; int font. Size; float leading; boolean active; public void start() { String param; font. Name = get. Parameter("font. Name"); if(font. Name == null) font. Name = "Not Found"; 18

param = get. Parameter("font. Size"); try { if(param != null) //if not found font.

param = get. Parameter("font. Size"); try { if(param != null) //if not found font. Size = Integer. parse. Int(param); else font. Size = 0; } catch(Number. Format. Exception e) { font. Size = -1; } param = get. Parameter("leading"); try { if(param != null) //if not found leading = Float. value. Of(param). float. Value(); else leading = 0; } catch(Number. Format. Exception e) { leading = -1; } 19

param = get. Parameter("account. Enabled"); if(param != null) active = Boolean. value. Of(param). boolean.

param = get. Parameter("account. Enabled"); if(param != null) active = Boolean. value. Of(param). boolean. Value(); } public void paint(Graphics g) { g. draw. String("Font name: " + font. Name, 0, 10); g. draw. String("Font Size: " + font. Size, 0, 20); g. draw. String("Leading: " + leading, 0, 42); g. draw. String("Account Active: " + active, 0, 58); } } 20

get. Code. Base() and get. Document. Base() import java. awt. *; import java. applet.

get. Code. Base() and get. Document. Base() import java. awt. *; import java. applet. *; import java. net. *; /* <applet code=Param. Demo_2. class width = 300 height = 300> </applet> */ public class Param. Demo_2 extends Applet { public void paint(Graphics g) { String msg; URL url = get. Code. Base(); msg = "Code Base: " + url. to. String(); g. draw. String(msg, 10, 20); url = get. Document. Base(); msg = "Document Base: " + url. to. String(); g. draw. String(msg, 10, 40); } } 21

The Audio. Clip Interface The Audio. Clip interface defines these methods: 1. play (

The Audio. Clip Interface The Audio. Clip interface defines these methods: 1. play ( ) – play a clip from the beginning. 2. stop ( ) – stop playing the clip. 3. loop ( ) – play the loop continuously. 4. get. Audio. Clip ( ) - After you have loaded an audio clip import java. applet. *; import java. awt. event. *; import java. awt. *; /* <applet code=Sound. Example width = 300 height = 300> </applet> */ public class Sound. Example extends Applet implements Mouse. Listener { Audio. Clip sound. File 1; Audio. Clip sound. File 2; 22

public void init() { sound. File 1 = get. Audio. Clip(get. Document. Base(), "c:

public void init() { sound. File 1 = get. Audio. Clip(get. Document. Base(), "c: \windows\media\ding. wav"); sound. File 2 = get. Audio. Clip(get. Document. Base(), "c: \windows\media\start. wav"); add. Mouse. Listener(this); set. Background(Color. yellow); sound. File 1. play(); } public void paint(Graphics g) { g. draw. String("Click to hear a sound", 20); } public void mouse. Clicked(Mouse. Event evt) { sound. File 2. play(); } public void mouse. Pressed(Mouse. Event evt) {} public void mouse. Released(Mouse. Event evt) {} public void mouse. Entered(Mouse. Event evt) {} public void mouse. Exited(Mouse. Event evt) {} } 23

Applet. Stub Interface The Applet. Stub interface provides a way to get information from

Applet. Stub Interface The Applet. Stub interface provides a way to get information from the run-time browser environment. The Applet class provides methods with similar names that call these methods. Methods public abstract boolean is. Active () The is. Active() method returns the current state of the applet. While an applet is initializing, it is not active, and calls to is. Active() return false. The system marks the applet active just prior to calling start(); after this point, calls to is. Active() return true. public abstract URL get. Document. Base () The get. Document. Base() method returns the complete URL of the HTML file that loaded the applet. This method can be used with the get. Image() or get. Audio. Clip() methods to load an image or audio file relative to the HTML file. public abstract URL get. Code. Base () The get. Code. Base() method returns the complete URL of the. class file that contains the 24 applet. This method can be used with the get. Image() method or the get. Audio. Clip() method to load an image or audio file relative to the. class file.

public abstract String get. Parameter (String name) The get. Parameter() method allows you to

public abstract String get. Parameter (String name) The get. Parameter() method allows you to get parameters from <PARAM> tags within the <APPLET> tag of the HTML file that loaded the applet. The name parameter of get. Parameter() must match the name string of the <PARAM> tag; name is case insensitive. The return value of get. Parameter() is the value associated with name; it is always a String regardless of the type of data in the tag. If name is not found within the <PARAM> tags of the <APPLET>, get. Parameter() returns null. public abstract void applet. Resize (int width, int height) The applet. Resize() method is called by the resize method of the Applet class. The method changes the size of the applet space to width x height. The browser must support changing the applet space; if it doesn't, the size remains unchanged. 25

The Delegation Event Model 1. The modern approach to handling events is based on

The Delegation Event Model 1. The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. 2. Its concept is quite simple: a source generates an event and sends it to one or more listeners. 3. In this scheme, the listener simply waits until it receives an event. 4. Once received, the listener processes the event and then returns. 5. 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. 6. A user interface element is able to “delegate” the processing of an event to a separate piece of code. Events 1. In the delegation model, an event is an object that describes a state change in a source. 2. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. 3. 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. 4. Event 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 26 failure occurs, or an operation is completed.

Event Sources 1. A source is an object that generates an event. 2. This

Event Sources 1. A source is an object that generates an event. 2. This occurs when the internal state of that object changes in some way. 3. Sources may generate more than one type of event. 4. A source must register listeners in order for the listeners to receive notifications about a specific type of event. 5. Each type of event has its own registration method. 6. Here is the general form: public void add. Type. Listener(Type. Listener el) 7. Here, type is the name of the event and el is a reference to the event listener. 8. For example the method that registers a keyboard event listener is called add. Key. Listener(). 9. The method that registers a mouse motion listener is called add. Mouse. Listener(). 10. When an event occurs, all registered listeners are notified and receive a copy of the event object. 11. This known as multicasting the event. Some sources may allow only one listener to register. 12. The general form of such method is this: 27 public void add. Type. Listener(Type. Listener el) throws java. util. Too. Many. Listeners. Exception

13. Here, Type is the name of the event and el is a reference

13. Here, Type is the name of the event and el is a reference to the event listener. 14. When such an event occurs, the registered listener is notified. This is known a s unicasting the event. 15. A source must also provide a method that allows a listener to unregister an interest in a specific type of event. 16. The general form of such a method is this: public void remove. Type. Listener(Type. Listener el) 17. Here, Type is the name of the event and el is reference to the event listener. 18. For Example, to remove a keyboard listener, you would call remove. Key. Listener(). 19. The methods that add or remove listeners are privided by the source that generates events. 20. For example, the Component class provides methods to add and remove keyboard and mouse event listeners. Event Listeners 21. A Listener is an object that is notified when an event occurs. It has major requirements. 22. First, it must have been registered with one or more sources to receive notification about specific type of events. 23. Second, it must implement methods to receive and process these notifications. 28

24. The methods that receive and pricess events are defined in a set of

24. The methods that receive and pricess events are defined in a set of interfaces found in java. awt. event. 25. For example, the Mouse. Motion. Listener interface defines two method to receive notifications when the mouse is dragged or moved. 26. Any object may receive and process one or both of these events if it provides an implementation of this interface. 29

EVENT CLASSES 30

EVENT CLASSES 30

Event Classes 1. The classes that represent events are at the core of Java’s

Event Classes 1. The classes that represent events are at the core of Java’s event handling mechanism. 2. At the root of the Java event class hierarchy is Event. Object, which is in java. util. 3. It is the superclass for all events. Its one constructor is shown here: Event. Object(Object src) 4. Here, src is the object that generates this event. 5. Event. Object contains two methods: get. Source() and to. String(). 6. The get. Source() method returns the source of the event. 7. Its general form is shown here: Object get. Source() 8. As expected, to. String() returns the string equivalent of the event. 9. The AWTEvent, defined within the java. awt package, is a subclass of Event. Object. 10. It is the superclass of all AWT – based events used by the delegation event model. 11. Its get. ID() method can be used to determine the type of the event. The signature of this method is shown here: int get. ID() 31

The package java. awt. event defines several types of events that are generated by

The package java. awt. event defines several types of events that are generated by various user interface elements. EVENT CLASSES DESCRIPTION Action. Event Generated when a button is pressed, a list item is double - clicked, or a menu item is selected. Adjustment. Event Generated when a scroll bar is manupulated Component. Event Generated when a component is hidden, moved, resized, or becomes visible. Container. Event Generated when a component is added to or removed from a container. Focus. Event Generated when a component gains or loses keyboard focus. Input. Event Abstract super class for all component input event classes. Item. Event 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 deselecte. Key. Event Generated when input is received from the keyboard. Mouse. Event Generated when the mouse is dragged, moved, clicked, pressed, or , released; also generated when the mouse enters or exits a component. Mouse. Wheel. Event Generated when the mouse wheel is moved. Text. Event Generated when the value of a text area or text field is changed. Windows. Event Generated when a window is activated, closed, deactivated, deiconified, 32 iconified, opened, or quit.

The Action. Event Class 1. An Action. Event is generated when a button is

The Action. Event Class 1. An Action. Event is generated when a button is pressed, a list item is double - clicked, or a menu item is selected. 2. The Action. Event class defines fout integer constants that can be used to identify any modifiers associated with an action event: ALT_MASK, CTRL_MASK, META_MASK, and SHIFT_MASK. 3. In addition. There is an integer constant, ACTION_PERFORMED, which can be used to identify action events. Action. Event has these three constructors: Action. Event(Object src, int type, String cmd) Action. Event(Object src, int type, String cmd, int modifiers) Action. Event(Object src, int type, String cmd, long when, int modifiers) 4. Here, src is a reference to the object that generated this event. 5. The type of the event is specified by type, and its command string is cmd. 6. The argument modifiers indicates which modifier key were pressed when the event was generated. 7. The when parameter specifies when the event occurred. 33

Action Event Example Button Click import java. applet. *; import java. awt. event. *;

Action Event Example Button Click import java. applet. *; import java. awt. event. *; /* <applet code="Button_Setnull. class" height=300 width=300> </applet> */ public class Button_Setnull extends Applet implements Action. Listener { Text. Field tf 1, tf 2, tf 3; Label l 1, l 2, l 3; Button b 1; int x, y, z; public void init() { set. Background(Color. red); set. Foreground(Color. green); //set. Title("Addition of Two Numbers"); set. Layout(null); 34

l 1 = new Label("Enter the A Value"); l 1. set. Bounds(0, 0, 100,

l 1 = new Label("Enter the A Value"); l 1. set. Bounds(0, 0, 100, 25); l 2 = new Label("Enter the B Value"); l 2. set. Bounds(0, 50, 100, 25); l 3 = new Label("Addition of the Two Numbers"); l 3. set. Bounds(0, 100, 170, 25); tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf 2 = new Text. Field(10); tf 2. set. Bounds(200, 50, 100, 25); tf 3 = new Text. Field(10); tf 3. set. Bounds(200, 100, 25); b 1 = new Button("Click Addition"); b 1. set. Bounds(100, 150, 25); add(l 1); add(tf 1); add(l 2); add(tf 2); add(l 3); add(tf 3); add(b 1); b 1. add. Action. Listener(this); } 35

public void action. Performed(Action. Event ae) { if(ae. get. Action. Command(). equals("Click Addition")) {

public void action. Performed(Action. Event ae) { if(ae. get. Action. Command(). equals("Click Addition")) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x + y; tf 3. set. Text(String. value. Of(z)); } } } 36

Action Event Example List Box item Double Click import java. applet. *; import java.

Action Event Example List Box item Double Click import java. applet. *; import java. awt. event. *; /* <applet code=“Listbox_Setnull. class" height=300 width=1000> </applet> */ public class Listbox_Setnull extends Applet implements Action. Listener { Text. Field tf 1, tf 2, tf 3; Label l 1, l 2, l 3; List ls; int x, y, z; public void init() { set. Background(Color. red); set. Foreground(Color. green); set. Layout(null); l 1 = new Label("Enter the A Value"); l 1. set. Bounds(0, 0, 100, 25); l 2 = new Label("Enter the B Value"); l 2. set. Bounds(0, 50, 100, 25); l 3 = new Label("Compute the Two Numbers"); 37 l 3. set. Bounds(0, 100, 170, 25);

tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf

tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf 2 = new Text. Field(10); tf 2. set. Bounds(200, 50, 100, 25); tf 3 = new Text. Field(10); tf 3. set. Bounds(200, 100, 25); ls = new List(); ch. set. Bounds(100, 150, 25); ls. add(""); ls. add("Addition"); ls. add("Subtraction"); ls. add("Multiplication"); ls. add("Division"); ls. add("Clear"); ls. add("Total No. of Item"); ls. add("Get Selected Item"); add(l 1); add(tf 1); add(l 2); add(tf 2); add(l 3); add(tf 3); add(ls); ls. add. Action. Listener(this); } 38

public void action. Performed(Action. Event ae) { if(ls. get. Selected. Index() == 1) {

public void action. Performed(Action. Event ae) { if(ls. get. Selected. Index() == 1) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x + y; tf 3. set. Text(String. value. Of(z)); } if(ls. get. Selected. Index() == 2) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x - y; tf 3. set. Text(String. value. Of(z)); } 39

} if(ls. get. Selected. Index() == 3) { x = Integer. parse. Int(tf 1.

} if(ls. get. Selected. Index() == 3) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x * y; tf 3. set. Text(String. value. Of(z)); } if(ls. get. Selected. Index() == 4) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x / y; tf 3. set. Text(String. value. Of(z)); } if(ls. get. Selected. Index() == 5) { tf 1. set. Text(""); tf 2. set. Text(""); tf 3. set. Text(""); } if(ls. get. Selected. Index() == 6) { int a = ch. get. Item. Count(); tf 3. set. Text(String. value. Of(a)); } if(ls. get. Selected. Index() == 7) { tf 3. set. Text(ch. get. Item(ch. get. Selected. Index())); 40 } }

You can obtain the command name for the invoking Action. Event object by using

You can obtain the command name for the invoking Action. Event object by using the get. Action. Command() method, shown here: String get. Action. Command() For example, when a button is pressed, and action event is generated that has a command name equal to the label on that button. The get. Modifiers() method returns a value that indicates which modifier keys(ALT, CTRL, META and SHIFT) were pressed when the event was generated. Its form is shown here: String get. Modifiers() The Adjustment. Event Class An Adjustement. Event is generated by a scroll bar. There are five types of adjustment events. The Adjustement. Event class defines integer constants that can be used to identify them. BLOCK_DECREMENT – The user clicked inside the scroll bar to decrease its value. BLOCK_INCREMENT – The user Clicked inside the scroll bar to increase its value. TRACK – The slider was dragged. UNIT_DECREMENT – The button at the end of the scroll bar was clicked to decrease its value UNIT_INCREMENT – The button at the end of the scroll bar was clicked to increase its value. 41

In addition, there is an integer constant, ADJUSTMETN_VALUE_CHANGED, that indicates that a change has

In addition, there is an integer constant, ADJUSTMETN_VALUE_CHANGED, that indicates that a change has occurred. Here is one Adjustment. Event constructor: Adjustment. Event(Adjustable src, int id, int type, int data) Here, src is a reference to the object that generated this event. The id equals ADJUSTEMENT_VALUE_CHANGED. The type of the event is specified by type, and its associated data is data. The get. Adjustable() method returns the object that generated the event. Its form is shown here: Adjustable get. Adjustable() The type of the adjustement event may be obtained by the get. Adjustment. Type() method. It returns one of the constant defined by Adjustment. Event. The general form is shown here: int get. Adjustment. Type() The amount of the adjustement can be obtained from the get. Value() method, shown here int get. Value() 42

import java. applet. *; Adjustment. Event Example Horizontal and Vertical Scrollbar Changed import java.

import java. applet. *; Adjustment. Event Example Horizontal and Vertical Scrollbar Changed import java. awt. *; import java. awt. event. *; /* <applet code="Scroll_Setnull. class" height=300 width=1000> </applet> */ public class Scroll_Setnull extends Applet implements Adjustment. Listener { Text. Field tf 1, tf 2, tf 3; Label l 1, l 2, l 3; Scrollbar sbh, sbv; int x, y, z; public void init() { set. Background(Color. red); set. Foreground(Color. green); set. Layout(null); l 1 = new Label("Enter the A Value"); l 1. set. Bounds(0, 0, 100, 25); l 2 = new Label("Enter the B Value"); l 2. set. Bounds(0, 50, 100, 25); l 3 = new Label("Compute the Two Numbers"); 43 l 3. set. Bounds(0, 100, 170, 25);

tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf

tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf 2 = new Text. Field(10); tf 2. set. Bounds(200, 50, 100, 25); tf 3 = new Text. Field(10); tf 3. set. Bounds(200, 100, 25); int height = Integer. parse. Int(get. Parameter("height")); int width = Integer. parse. Int(get. Parameter("width")); sbh = new Scrollbar(Scrollbar. HORIZONTAL, 0, 1, 0, height); sbh. set. Bounds(0, 275, 975, 25); sbv = new Scrollbar(Scrollbar. VERTICAL, 0, 1, 0, width); sbv. set. Bounds(975, 0, 25, 300); sbh. set. Unit. Increment(50); sbh. set. Block. Increment(50); sbv. set. Unit. Increment(20); sbv. set. Block. Increment(20); add(l 1); add(tf 1); add(l 2); add(tf 2); add(l 3); add(tf 3); add(sbh); add(sbv); sbh. add. Adjustment. Listener(this); sbv. add. Adjustment. Listener(this); } 44

public void adjustment. Value. Changed(Adjustment. Event ae) { if(sbh. get. Value() == 50) {

public void adjustment. Value. Changed(Adjustment. Event ae) { if(sbh. get. Value() == 50) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x + y; tf 3. set. Text(String. value. Of(z)); } if(sbh. get. Value() == 100) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x - y; tf 3. set. Text(String. value. Of(z)); } 45

if(sbh. get. Value() == 150) { x = Integer. parse. Int(tf 1. get. Text());

if(sbh. get. Value() == 150) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x * y; tf 3. set. Text(String. value. Of(z)); } if(sbh. get. Value() == 200) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x / y; tf 3. set. Text(String. value. Of(z)); } if(sbh. get. Value() == 250) { tf 1. set. Text(""); tf 2. set. Text(""); } } } tf 3. set. Text(""); 46

The Component. Event Class A Component. Event is generated when the size, position, or

The Component. Event Class A Component. Event is generated when the size, position, or visibility of a component is changed. There are four types of component events. The Component. Event class defines integer constants that can be used to identify them. The constant and their meanings are shown here: COMPONENT_HIDDEN The component was hidden COMPONENT_MOVED - The component was moved COMPONENT_RESIZED - The component was resized COMPONENT_SHOWN - The component became visible Component. Event has this constructor Component. Event(Component src, int type) Here, src is a reference to the object that generated this event. The type of the event is specified by type. Component. Event is the superclass either directly or indirectly of Container. Event, Focus. Event, Key. Event, Mouse. Event, and Window. Event. The get. Component() method returns the component that generated the event. It is shown here: 47 Component get. Component()

The Container. Event Class 1. A Container. Event is generated when a component is

The Container. Event Class 1. A Container. Event is generated when a component is added to or removed from a container. 2. There are two types of container events. 3. The Container. Event class defines int constants that can be used to identify them: COMPONENT_ADDED and COMPONENET_REMOVED. 4. They indicate that a component has been added or removed form the container. 5. Container. Event is a subclass of Component. Event and has this constructor: Container. Event(Component src, int type, Component comp) Here, src is reference to the container that generated this event. The type of the event is specified by type, and the component that has been added to or removed from the container is comp. You can obtain a reference to the container that generated this event by using the get. Cotnainer() method, shown here: Container get. Container() The get. Child() method returns a reference to the component that was added to or removed from the container. Its general form is shown here: 48 Component get. Child()

The Focus. Event Class A Focus. Event is generated when a component gains or

The Focus. Event Class A Focus. Event is generated when a component gains or loses input focus. These events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST Focus. Event is a subclass of Component. Event and has threse constructor: Focus. Event(Component src, int type) Focus. Event(Component src, int type, boolean temporary. Flag, Component other) 1. Here, src is a reference to the component that generated this event. 2. The type of the event is specified by type. 3. The argument temporary. Flag is set to true if the focus event is temporary. 4. Otherwise, it is set to false. 5. The other component involved in the focus change, called the apposite component, is passed in other. 6. Therefore, if a FOCUS_GAINED event occurred, other will refer to the component that lost focus. 7. Conversely, if a FOCUS_LOST event occurred, other will refer to the component that gains focus. 49

import java. applet. *; Focus. Event Example Focus Gained and Focus Lost in Text.

import java. applet. *; Focus. Event Example Focus Gained and Focus Lost in Text. Box import java. awt. *; import java. awt. event. *; /* <applet code="Focus_Event. class" height=300 width=1000> </applet> */ public class Focus_Event extends Applet implements Focus. Listener { Text. Field tf 1, tf 2, tf 3; public void init() { set. Background(Color. red); set. Foreground(Color. green); } tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf 2 = new Text. Field(10); tf 2. set. Bounds(200, 50, 100, 25); tf 3 = new Text. Field(10); tf 3. set. Bounds(200, 100, 25); add(tf 1); add(tf 2); add(tf 3); tf 1. add. Focus. Listener(this); tf 2. add. Focus. Listener(this); 50

public void focus. Gained(Focus. Event fe) { tf 2. set. Text("Focus Gained"); } public

public void focus. Gained(Focus. Event fe) { tf 2. set. Text("Focus Gained"); } public void focus. Lost(Focus. Event fe) { tf 1. set. Text("Focus Lost"); } } 51

You can determine the other component by calling get. Opposite. Component(), shown here. Component

You can determine the other component by calling get. Opposite. Component(), shown here. Component get. Opposite. Component() The is. Temporary() method indicates if this focus change is temporary. Its form is shown here: boolean is. Temprorary() The method returns true if the change is temporary. Otherwise, it returns false. The Mouse. Event Class There are eight types of mouse events. The Mouse. Event 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. 52

Mouse. Event is a subclass of Input. Event. Here is one of its constructor.

Mouse. Event is a subclass of Input. Event. Here is one of its constructor. Mouse. Event(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggers. Popup 1. Here, src is a reference to the component that generated the event. 2. The type of the event is specified by type. 3. The system time at which the mouse event occurred is passed in when. 4. The modifiers aregument indicates which modifiers were pressed when a mouse event occurred. 5. The coordinates of the mouse are passed in x and y. 6. The click count is passed in clicks. 7. The triggers. Popup flag indicates if this event causes a pop – up menu to appear on this platform Methods Description int get. X() and int get. Y() These retrun the X and Y coordinates of the mouse when the event occured Point get. Point() It returns a Point object that contains the X, Y coordinates in its integer members. get. Click. Count() The methods obtains the number of mouse clicks for this event is. Popup. Trigger() This method tests if this event causes a pop – up menu to appear on 53 this platform

import java. awt. *; Mouse. Event Example import java. awt. event. *; import java.

import java. awt. *; Mouse. Event Example import java. awt. event. *; import java. applet. *; /* <applet code="Mouse" width=500 height=500> </applet> */ public class Mouse extends Applet implements Mouse. Listener, Mouse. Motion. Listener { int X=0, Y=20; String msg="Mouse. Events"; public void init() { add. Mouse. Listener(this); add. Mouse. Motion. Listener(this); set. Background(Color. black); set. Foreground(Color. red); } public void mouse. Entered(Mouse. Event m) { set. Background(Color. magenta); show. Status("Mouse Entered"); repaint(); } public void mouse. Exited(Mouse. Event m) { set. Background(Color. black); show. Status("Mouse Exited"); repaint(); } in Mouse 54

public void mouse. Pressed(Mouse. Event m) { X=10; Y=20; msg="CCET"; set. Background(Color. green); repaint();

public void mouse. Pressed(Mouse. Event m) { X=10; Y=20; msg="CCET"; set. Background(Color. green); repaint(); } public void mouse. Released(Mouse. Event m) { X=10; Y=20; msg="Engineering"; set. Background(Color. blue); repaint(); } public void mouse. Moved(Mouse. Event m) { X=m. get. X(); Y=m. get. Y(); msg="College"; set. Background(Color. white); show. Status("Mouse Moved"); repaint(); } 55

public void mouse. Dragged(Mouse. Event m) { msg="CSE"; set. Background(Color. yellow); show. Status("Mouse Moved"+m.

public void mouse. Dragged(Mouse. Event m) { msg="CSE"; set. Background(Color. yellow); show. Status("Mouse Moved"+m. get. X()+" "+m. get. Y()); repaint(); } public void mouse. Clicked(Mouse. Event m) { msg="Students"; set. Background(Color. pink); show. Status("Mouse Clicked"); repaint(); } public void paint(Graphics g) { g. draw. String(msg, X, Y); } } 56

The Mouse. Wheel. Event Class The Mouse. Wheel. Event class encapsulates a mouse wheel

The Mouse. Wheel. Event Class The Mouse. Wheel. Event class encapsulates a mouse wheel event. If a mouse has a wheel, it is located between the left and right buttons. Mouse wheels, are used for scrolling. Mouse. Wheel. Event defines these two integer constants. WHEEL_BLOCK_SCROLL WHEEL_UNIT_SCROLL - A page – up or page – down scroll event occurred - A line – up or line – down scroll event occured Mouse. Wheel. Event defines the following constructor: Mouse. Wheel. Event(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggers. Popup, int scroll. How, int amount, int count) Here, src is a reference to the object 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 the event occurred. The coordinates of the mouse are passed in x and y. The number of clicks the wheel has rotated is passed in clicks. The triggers Popup flag indicates if this event causes a pop – up menu to appear on this platform. The scroll. How value must be either is passes in amount. The count parameter indicates the number of roational units that the wheel moved. 57

Methods Description int get. Wheel. Rotation() It returns the number of rotational units. If

Methods Description int get. Wheel. Rotation() It returns the number of rotational units. If the value is positive, the wheel moved conterclockwise. If the value is negative, the wheel moved clockwise. int get. Scroll. Type() It returns either WHEEL_UNIT_SCORLL or WHEEL_BLOCK_SCROLL int get. Scroll. Amount() If the scroll type is WHEEL_UNIT_SCROLL you can obtain the number of units to scroll by calling get. Scroll. Amount(). The Input. Event Class 1. The abstract class Input. Event is a subclass of Component. Event and is the superclass for component input events. 2. Its subclasses are key. Event and Mouse. Event. Input. Event defines several integer constants that represent any modifiers, such as the control key being pressed, that might be assocated with the event. 3. Originally, the Input. Event class defined the following eight values to represent the modifiers. ALT_MASK BUTTON 2_MASK BUTTON 3_MASK SHIFT_MASK BUTTON 1_MASK CTRL_MASK META_MASK 58

4. However, because of possible conflicts between the modifiers used by keyboard events and

4. However, because of possible conflicts between the modifiers used by keyboard events and mouse events, and other issues, Java 2 version 1. 4, added the following extended modifier values. ALT_DOWN_MASK BUTTON 2_DOWN_MASK BUTTON 3_DOWN_MASK SHIFT_DOWN_MASK BUTTON 1_DOWN_MASK CTRL_DOWN_MASK META_DOWN_MASK 5. When writing new code, it is recommended that you use the new, extended modifiers rather that the original modifiers. 6. To test if a modifier was pressed at the time an event is generated, use the is. Alt. Down(), is. Alt. Graph. Down(), is. Control. Down(), is. Meta. Down(), and is. Shift. Down() methods. 7. The forms of these methods are shown here: boolean is. Alt. Down() boolean is. Alt. Graph. Down() boolean is. Control. Down() boolean is. Meta. Down() boolean is. Shift. Down() 59

You can obtain a value that contains all of the original modifer flags by

You can obtain a value that contains all of the original modifer flags by calling the get. Modifiers() method. It is shown here: int get. Modifiers() You can obtain the extended modifiers by called get. Modifiers. Ex(), which is shown here: int get. Modifiers. Ex() The Item. Event Class 1. An Item. Event is generated when a check box or a list item is clicked or when a checkable menu item is selected or deselected. 2. There are two types of item events, which are identified by the following integer constants. DESELECTED - The user deselected an item SELECTED - The user selected an item In addition, Item. Event defines one integer constant, ITEM_STATE_CHANGED, that signifies a change of state. Item. Event(Item. Selectable src, int type, Object entry, int state) 60

3. Here, src is a reference to the component that generated this event. 4.

3. Here, src is a reference to the component that generated this event. 4. For example, this might be a list or choice element. 5. The type of the event is specified by type. 6. The specific item that generated the item event is passed in entry. The current state of that item is in state. 7. The get. Item() method can be used to obtain a reference to the item that generated an event. Its signature is shown here: Object get. Item() 8. The get. Item. Selectable() method can be used to obtain a reference to the Item. Selectable object that generated an event. Its general form shown here: item. Selectable get. Item. Selectable() 9. Lists and choices are examples of user interface elements that implement the Item. Selectable interface. 10. The get. State. Change() method returns the state change for the event. It is shown here: int get. State. Change() 61

import java. applet. *; Item. Event Example in Checkbox import java. awt. *; import

import java. applet. *; Item. Event Example in Checkbox import java. awt. *; import java. awt. event. *; /* <applet code="Checkbox_Setnull. class" height=300 width=1000> </applet> */ public class Checkbox_Setnull extends Applet implements Item. Listener { Text. Field tf 1, tf 2, tf 3; Label l 1, l 2, l 3; Checkbox ch 1, ch 2, ch 3, ch 4, ch 5; int x, y, z; public void init() { set. Background(Color. red); set. Foreground(Color. green); set. Layout(null); l 1 = new Label("Enter the A Value"); l 1. set. Bounds(0, 0, 100, 25); l 2 = new Label("Enter the B Value"); l 2. set. Bounds(0, 50, 100, 25); l 3 = new Label("Addition of the Two Numbers"); l 3. set. Bounds(0, 100, 170, 25); 62

tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf

tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf 2 = new Text. Field(10); tf 2. set. Bounds(200, 50, 100, 25); tf 3 = new Text. Field(10); tf 3. set. Bounds(200, 100, 25); ch 1 = new Checkbox("Addition"); ch 1. set. Bounds(100, 150, 25); ch 2 = new Checkbox("Subtraction"); ch 2. set. Bounds(250, 150, 25); ch 3 = new Checkbox("Multiplication"); ch 3. set. Bounds(400, 150, 25); ch 4 = new Checkbox("Division"); ch 4. set. Bounds(550, 150, 25); ch 5 = new Checkbox("Clear"); ch 5. set. Bounds(700, 150, 25); add(l 1); add(tf 1); add(l 2); add(tf 2); add(l 3); add(tf 3); add(ch 1); add(ch 2); add(ch 3); add(ch 4); add(ch 5); ch 1. add. Item. Listener(this); ch 2. add. Item. Listener(this); ch 3. add. Item. Listener(this); ch 4. add. Item. Listener(this); ch 5. add. Item. Listener(this); } 63

public void item. State. Changed(Item. Event ie) { if(ch 1. get. State()==true) { x

public void item. State. Changed(Item. Event ie) { if(ch 1. get. State()==true) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x + y; tf 3. set. Text(String. value. Of(z)); } if(ch 2. get. State()==true) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x - y; tf 3. set. Text(String. value. Of(z)); } 64

if(ch 3. get. State()==true) { x = Integer. parse. Int(tf 1. get. Text()); y

if(ch 3. get. State()==true) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x * y; tf 3. set. Text(String. value. Of(z)); } if(ch 4. get. State()==true) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x / y; tf 3. set. Text(String. value. Of(z)); } if(ch 5. get. State()==true) { tf 1. set. Text(""); } } } tf 2. set. Text(""); tf 3. set. Text(""); 65

import java. applet. *; Item. Event Example in Checkbox. Group import java. awt. *;

import java. applet. *; Item. Event Example in Checkbox. Group import java. awt. *; import java. awt. event. *; /* <applet code="Checkboxgroup_Setnull. class" height=300 width=1000> </applet> */ public class Checkboxgroup_Setnull extends Applet implements Item. Listener { Text. Field tf 1, tf 2, tf 3; Label l 1, l 2, l 3; Checkbox ch 1, ch 2, ch 3, ch 4, ch 5; Checkbox. Group cbg; int x, y, z; public void init() { set. Background(Color. red); set. Foreground(Color. green); set. Layout(null); cbg = new Checkbox. Group(); l 1 = new Label("Enter the A Value"); l 1. set. Bounds(0, 0, 100, 25); l 2 = new Label("Enter the B Value"); l 2. set. Bounds(0, 50, 100, 25); 66 l 3 = new Label("Compute the Two Numbers"); l 3. set. Bounds(0, 100, 170, 25);

tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf

tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf 2 = new Text. Field(10); tf 2. set. Bounds(200, 50, 100, 25); tf 3 = new Text. Field(10); tf 3. set. Bounds(200, 100, 25); ch 1 = new Checkbox("Addition", cbg, false); ch 1. set. Bounds(100, 150, 25); ch 2 = new Checkbox("Subtraction", cbg, false); ch 2. set. Bounds(250, 150, 25); ch 3 = new Checkbox("Multiplication", cbg, false); ch 3. set. Bounds(400, 150, 25); ch 4 = new Checkbox("Division", cbg, false); ch 4. set. Bounds(550, 150, 25); ch 5 = new Checkbox("Clear", cbg, false); ch 5. set. Bounds(700, 150, 25); add(l 1); add(tf 1); add(l 2); add(tf 2); add(l 3); add(tf 3); add(ch 1); add(ch 2); add(ch 3); add(ch 4); add(ch 5); ch 1. add. Item. Listener(this); ch 2. add. Item. Listener(this); ch 3. add. Item. Listener(this); ch 4. add. Item. Listener(this); ch 5. add. Item. Listener(this); } 67

public void item. State. Changed(Item. Event ie) { if(ch 1. get. State()==true) { x

public void item. State. Changed(Item. Event ie) { if(ch 1. get. State()==true) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x + y; tf 3. set. Text(String. value. Of(z)); l 3. set. Visible(true); tf 3. set. Visible(true); } if(ch 2. get. State()==true) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x - y; tf 3. set. Text(String. value. Of(z)); } 68

if(ch 3. get. State()==true) { x = Integer. parse. Int(tf 1. get. Text()); y

if(ch 3. get. State()==true) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x * y; tf 3. set. Text(String. value. Of(z)); } if(ch 4. get. State()==true) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x / y; tf 3. set. Text(String. value. Of(z)); } if(ch 5. get. State()==true) { tf 1. set. Text(""); } } } tf 2. set. Text(""); tf 3. set. Text(""); 69

Item. Event Example in Choice Box import java. applet. *; import java. awt. event.

Item. Event Example in Choice Box import java. applet. *; import java. awt. event. *; /* <applet code="Choicebox_Setnull. class" height=300 width=1000> </applet> */ public class Choicebox_Setnull extends Applet implements Item. Listener { Text. Field tf 1, tf 2, tf 3; Label l 1, l 2, l 3; Choice ch; int x, y, z; public void init() { set. Background(Color. red); set. Foreground(Color. green); set. Layout(null); l 1 = new Label("Enter the A Value"); l 1. set. Bounds(0, 0, 100, 25); l 2 = new Label("Enter the B Value"); l 2. set. Bounds(0, 50, 100, 25); l 3 = new Label("Compute the Two Numbers"); 70 l 3. set. Bounds(0, 100, 170, 25);

tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf

tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf 2 = new Text. Field(10); tf 2. set. Bounds(200, 50, 100, 25); tf 3 = new Text. Field(10); tf 3. set. Bounds(200, 100, 25); ch = new Choice(); ch. set. Bounds(100, 150, 25); ch. add(""); ch. add("Addition"); ch. add("Subtraction"); ch. add("Multiplication"); ch. add("Division"); ch. add("Clear"); ch. add("Total No. of Item"); ch. add("Get Selected Item"); add(l 1); add(tf 1); add(l 2); add(tf 2); add(l 3); add(tf 3); add(ch); ch. add. Item. Listener(this); } 71

public void item. State. Changed(Item. Event ie) { if(ch. get. Selected. Index() == 1)

public void item. State. Changed(Item. Event ie) { if(ch. get. Selected. Index() == 1) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x + y; tf 3. set. Text(String. value. Of(z)); } if(ch. get. Selected. Index() == 2) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x - y; tf 3. set. Text(String. value. Of(z)); } 72

} if(ch. get. Selected. Index() == 3) { x = Integer. parse. Int(tf 1.

} if(ch. get. Selected. Index() == 3) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x * y; tf 3. set. Text(String. value. Of(z)); } if(ch. get. Selected. Index() == 4) { x = Integer. parse. Int(tf 1. get. Text()); y = Integer. parse. Int(tf 2. get. Text()); z = x / y; tf 3. set. Text(String. value. Of(z)); } if(ch. get. Selected. Index() == 5) { tf 1. set. Text(""); tf 2. set. Text(""); tf 3. set. Text(""); } if(ch. get. Selected. Index() == 6) { int a = ch. get. Item. Count(); tf 3. set. Text(String. value. Of(a)); } if(ch. get. Selected. Index() == 7) { tf 3. set. Text(ch. get. Item(ch. get. Selected. Index())); 73 } }

The Key. Event Class 1. A Key. Event is generated when keyboard input occurs.

The Key. Event Class 1. A Key. Event is generated when keyboard input occurs. 2. There are three types of key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED and KEY_TYPED. 3. The first two events are generated when any key is pressed or released. 4. The last event occurs only when a character is generated. 5. Remember, not all key presses result in characters. 6. For example, pressing the SHIFT key does not generate a character. 7. There are many other integer constants that are defined by Key. Event. 8. 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_UP VK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWN VK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL 74

9. The VK constants specify virtual key codes and are independent of any modifiers,

9. The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or alt. Key. Event is a subclass of Input. Event. 10. Here are two of its constructors: Key. Event(Component src, int type, long when, int modifiers, int code) Key. Event(Component src, int type, long when, int modifiers, int code, char ch) 11. Here, src is a reference to the component that generated the event. 12. The type of the event is specified by type. 13. The system time at which the key was pressed is passed in when. 14. The modifiers argument indicates which modifiers where pressed when this key event occurred. 15. The virutal key code, such as VK_UP, VK_A, and so forth, is passed in code. 16. The character equivalent is passed in ch. If no valid character exists, then ch contains CHAR_UNDEFINED. 17. For KEY_TYPED events, code will contain VK_UNDEFINED. 18. The Key. Event class defines several methods, but the most commonly used ones are get. Key. Char(), which returns the character that was entered, and get. Key. Code(), which returns the key code. 75

//the key event handles import java. awt. *; import java. awt. event. *; import

//the key event handles import java. awt. *; import java. awt. event. *; import java. applet. *; /* <applet code=Key_Event. class width=300 height=100> </applet> */ public class Key_Event extends Applet implements Key. Listener { String msg=""; int x=10, y=20; public void init() { add. Key. Listener(this); } public void key. Pressed(Key. Event ke) { show. Status("Key Down"); } public void key. Released(Key. Event ke) { show. Status("Key Up"); } public void key. Typed(Key. Event ke) { msg+=ke. get. Key. Char(); repaint(); } public void paint(Graphics g) { g. draw. String(msg, x, y); } } Key. Event Example in Keyboard 76

Their general forms are shown here: char get. Key. Char() int get. Key. Code()

Their general forms are shown here: char get. Key. Char() int get. Key. Code() If not valid character is available, then get. Key. Char() returns CHAR_UNDEFINED. When a KEY_TYPED event occurs, get. Key. Code() returns VK_UNDEFINED The Text. Event Class Instances of this class describe text events. These are generated by text fields and text areas when characters are entered by a user or program. Text. Event defines the integer constant TEXT_VALUE_CHANGED. The one constructor for this class is shown here: Text. Event(Object src, int type) Here, src is a reference to the object that generated this event. The type of the event is specified by type. 77

import java. applet. *; Text. Event Example in Textbox import java. awt. *; import

import java. applet. *; Text. Event Example in Textbox import java. awt. *; import java. awt. event. *; /* <applet code="Text_Event. class" height=300 width=1000> </applet> */ public class Text_Event extends Applet implements Text. Listener { Text. Field tf 1, tf 2, tf 3; public void init() { set. Background(Color. red); set. Foreground(Color. green); tf 1 = new Text. Field(10); tf 1. set. Bounds(200, 0, 100, 25); tf 2 = new Text. Field(10); tf 2. set. Bounds(200, 50, 100, 25); tf 3 = new Text. Field(10); tf 3. set. Bounds(200, 100, 25); add(tf 1); add(tf 2); add(tf 3); tf 1. add. Text. Listener(this); tf 2. add. Text. Listener(this); } public void text. Value. Changed(Text. Event te) { tf 3. set. Text(tf 1. get. Text()); 78 } }

The Window. Event Class There are ten types of window events. The Window. Event

The Window. Event Class There are ten types of window events. The Window. Event class defines integer constants that can be used to identify them. The constant and their meanings are shown here: WINDOW_ACTIVATED - The window was activate WINDOW_CLOSED - The window has been closed WINDOW_CLOSING - The user requested that the window be closed WINDOW_DEACTIVATED - The window was deactivated. WINDOW_DEICONIFIED - The window was deiconified. WINDOW_GAINED_FOCUS - The window gained input focus. WINDOW_ICONIFIED - The window was iconified. WINDOW_LOST_FOCUS - The window lost input focus. WINDOW_OPENED - The window was opened. WINDOW_STATE_CHANGED - The state of the window changed. 79

Window. Event is a subclass of Component. Event. It defines the following constructor. Window.

Window. Event is a subclass of Component. Event. It defines the following constructor. Window. Event(Window src, int type) Here, src is a reference to the object that generated this event. The type of the event is type. The most commonly used method in this class is get. Window(). It returns the Window object that generated the event. Its general form is shown here: Window get. Window() 80

Event Classes Event Listener Interfaces Methods Action. Event Action. Listener void action. Performed(Action. Event

Event Classes Event Listener Interfaces Methods Action. Event Action. Listener void action. Performed(Action. Event ae) Adjustment. Event Adjustment. Listener void adjustment. Value. Changed(Adjustment. Event ae) Component. Event Component. Listener void component. Resized(Component. Event ce) void component. Moved(Component. Event ce) void component. Shown(Component. Event ce) void component. Hidden(Commonent. Event ce) Container. Event Container. Listener void component. Added(Container. Event ce) void component. Removed(Containter. Event ce) Focus. Event Focus. Listener void focus. Gained(Focus. Event fe) void focus. Lost(Focus. Event fe) Item. Event Item. Listener void item. State. Changed(Item. Event ie) Key. Event Key. Listener Void key. Pressed(Key. Event ke) Void key. Released(Key. Event ke) Void Key. Typed(Key. Event ke) Mouse. Event Mouse. Listener void mouse. Clicked(Mouse. Event me) void mouse. Entered(Mouse. Event me) void mouse. Exited(Mouse. Event me) void mouse. Pressed(Mouse. Event me) void mouse. Released(Mouse. Event me) Mouse. Motion. Listener void mouse. Dragged(Mouse. Event me) void mouse. Moved(Mouse. Event me) Input. Event 81

Event Classes Event Listener Interfaces Methods Mouse. Wheel. Event Mouse. Wheel. Listener void mouse.

Event Classes Event Listener Interfaces Methods Mouse. Wheel. Event Mouse. Wheel. Listener void mouse. Wheel. Moved(Mouse. Wheel. Event mwe) Text. Event Text. Listener void text. Changed(Text. Event te) Window. Event Windows. Listener void window. Activated(Window. Event we) void window. Closing(Window. Event we) void window. Deactivated(Window. Event we) void window. Deiconified(Window. Event we) void window. Iconified(Window. Event we) void window. Opened(Window. Event we) Window. Focus. Listener Void window. Gained. Focus(Window. Event we) Void window. Lost. Focus(Window. Event we) 82

Sources of Events Event Source Description Button Generates action events when the button is

Sources of Events Event Source Description Button Generates action events when the button is pressed. Checkbox Generates item event s when the check box is selected or deselected. Choice Generates item event s when the choice is changed. List Generates action event s when an item is double – clicked; generates item event when an item is selected or deselected. Menu Item Generates action event swhen a menu item is selected; generates item events when a checkable menu item is selected or deselected. Scrollbar Generates adjustment event when the scroll bar is manipulated. Text components Generates text events when the user enters a character. Window Generated window events when a window is activated, closed, deactivated, deiconified, opened, or quit. 83

The Collection Interface 1. The Collection interface is the foundation upon which the collections

The Collection Interface 1. The Collection interface is the foundation upon which the collections framework is built. 2. It declares the core methods that all collections will have. 3. Several of these methods can throw an Unsupported. Operation. Exception. 4. A Class. Cast. Exception is generated when one object is incompatible with another, such as when an attempt is made to add an incompatible object to a collection. 84

85

85

5. Objects are added to a collection by calling add( ). 6. Notice that

5. Objects are added to a collection by calling add( ). 6. Notice that add( ) takes an argument of type Object. 7. Because Object is a superclass of all classes, any type of object may be stored in a collection. 8. However, primitive types may not. 9. For example, a collection cannot directly store values of type int, char, double, and so forth. 10. You can add the entire contents of one collection to another by calling add. All( ). 11. You can remove an object by using remove( ). 12. To remove a group of objects, call remove. All( ). 13. You can remove all elements except those of a specified group by calling retain. All( ). 14. To empty a collection, call clear( ). 15. You can determine whether a collection contains a specific object by calling contains( ). 16. To determine whether one collection contains all the members of another, call contains. All( ). 17. You can determine when a collection is empty by calling is. Empty( ). 18. The number of elements currently held in a collection can be determined by calling size( ). 19. The to. Array( ) method returns an array that contains the elements stored in the invoking collection. 20. This method is more important than it might at first seem. 21. Often, processing the contents of a collection by using array-like syntax is advantageous. 22. By providing a pathway between collections and arrays, you can have the best of both worlds. 23. Two collections can be compared for equality by calling equals( ). 24. The precise meaning of “equality” may differ from collection to collection. 25. For example, you can implement equals( ) so that it compares the values of elements stored in the collection. 26. Alternatively, equals( ) can compare references to those elements. 27. One more very important method is iterator( ), which returns an iterator to a collection. 86

The List Interface 1. The List interface extends Collection and declares the behavior of

The List Interface 1. The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements. 2. Elements can be inserted or accessed by their position in the list, using a zero-based index. 3. A list may contain duplicate elements. 4. Note again that several of these methods will throw an Unsupported. Operation. Exception if the collection cannot be modified, and a Class. Cast. Exception is generated when one object is incompatible with another, such as when an attempt is made to add an incompatible object to a collection. 5. To the versions of add( ) and add. All( ) defined by Collection, List adds the methods add(int, Object) and add. All(int, Collection). 6. These methods insert elements at the specified index. 7. Also, the semantics of add(Object) and add. All(Collection) defined by Collection are changed by List so that they add elements to the end of the list. 8. To obtain the object stored at a specific location, call get( ) with the index of the object. 9. To assign a value to an element in the list, call set( ), specifying the index of the object to be changed. 10. To find the index of an object, use index. Of( ) or last. Index. Of( ). 87

88

88

import java. util. *; public class Demo. List { public static void main(String[] args)

import java. util. *; public class Demo. List { public static void main(String[] args) { List ls = new Linked. List(); for(int i=1; i<=5; i++){ ls. add(new String. Buffer("Object " + i)); } //display how many objects are in the collection System. out. println("The collection has " + ls. size() + "objects"); //Instantiate a List. Iterator li = ls. list. Iterator(); System. out. println("Forward Reading"); //Forward direction while(li. has. Next()){ System. out. println(" " + li. next()); } System. out. println("Backward Reading"); //backword direction while(li. has. Previous()) { System. out. println(" " + li. previous()); } } } 89

The Set Interface 1. The Set interface defines a set. 2. It extends Collection

The Set Interface 1. The Set interface defines a set. 2. It extends Collection and declares the behavior of a collection that does not allow duplicate elements. 3. Therefore, the add( ) method returns false if an attempt is made to add duplicate elements to a set. 4. It does not define any additional methods of its own. public class Set. Demo { public static void main(String[] args) { // Set example with implement Tree. Set s=new Tree. Set(); s. add("b"); s. add("a"); s. add("d"); s. add("c"); Iterator it=s. iterator(); while(it. has. Next()) { String value=(String)it. next(); System. out. println("Value : "+value); } } } 90

The Sorted. Set Interface 1. The Sorted. Set interface extends Set and declares the

The Sorted. Set Interface 1. The Sorted. Set interface extends Set and declares the behavior of a set sorted in ascending order. 2. In addition to those methods defined by Set, the Sorted. Set interface declares the methods. 3. Several methods throw a No. Such. Element. Exception when no items are contained in the invoking set. 4. A Class. Cast. Exception is thrown when an object is incompatible with the elements in a set. 5. A Null. Pointer. Exception is thrown if an attempt is made to use a null object and null is not allowed in the set. 6. Sorted. Set defines several methods that make set processing more convenient. 7. To obtain the first object in the set, call first( ). 8. To get the last element, use last( ). 9. You can obtain a subset of a sorted set by calling sub. Set( ), specifying the first and last object in the set. 10. If you need the subset that starts with the first element in the set, use head. Set( ). If you want the subset that ends the set, use tail. Set( ). 91

92

92

import java. util. Iterator; import java. util. Sorted. Set; import java. util. Tree. Set;

import java. util. Iterator; import java. util. Sorted. Set; import java. util. Tree. Set; public class Sorted. Set. Example { public static void main(String[] args) { Sorted. Set<String> ss=new Tree. Set<String>(); ss. add("a"); ss. add("e"); ss. add("g"); ss. add("b"); ss. add("c"); Iterator it=ss. iterator(); while(it. has. Next()) { String value=(String)it. next(); System. out. println("Value : "+value); } } } 93

COLLECTION CLASSES 94

COLLECTION CLASSES 94

Class Description Abstract. Collection Implements most of the Collection interface. Abstract. List Extends Abstract.

Class Description Abstract. Collection Implements most of the Collection interface. Abstract. List Extends Abstract. Collection and implements most of the List interface. Abstract. Sequential. List Extends Abstract. List for use by a collection that uses sequential rather than random access of its elements. Linked. List Implements a linked list by extending Abstract. Sequential. List. Array. List Implements a dynamic array by extending Abstract. List. Abstract. Set Extends Abstract. Collection and implements most of the Set interface. Hash. Set Extends Abstract. Set for use with a hash table. Linked. Hash. Set Extends Hash. Set to allow insertion-order iterations. Tree. Set Implements a set stored in a tree. Extends 95

1. The Array. List class extends Abstract. List and implements the List interface. 2.

1. The Array. List class extends Abstract. List and implements the List interface. 2. Array. List supports dynamic arrays that can grow as needed. 3. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. 4. But, sometimes, you may not know until run time precisely how large of an array you need. 5. To handle this situation, the collections framework defines Array. List. 6. In essence, an Array. List is a variable-length array of object references. 7. That is, an Array. List can dynamically increase or decrease in size. 8. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. 9. When objects are removed, the array may be shrunk. 10. Array. List has the constructors shown here: Array. List( ) Array. List(Collection c) Array. List(int capacity) The first constructor builds an empty array list. The second constructor builds an array list that is initialized with the elements of the collection c. The third constructor builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements 96 are added to an array list.

import java. util. *; class Array. List. Demo { public static void main(String args[])

import java. util. *; class Array. List. Demo { public static void main(String args[]) { // create an array list Array. List al = new Array. List(); System. out. println("Initial size of al: " + al. size()); // add elements to the array list al. add("C"); al. add("A"); al. add("E"); al. add("B"); al. add("D"); al. add("F"); al. add(1, "A 2"); System. out. println("Size of al after additions: " + al. size()); // display the array list System. out. println("Contents of al: " + al); // Remove elements from the array list al. remove("F"); al. remove(2); System. out. println("Size of al after deletions: " + al. size()); System. out. println("Contents of al: " + al); } } 97

The Linked. List Class 1. The Linked. List class extends Abstract. Sequential. List and

The Linked. List Class 1. The Linked. List class extends Abstract. Sequential. List and implements the List interface. 2. It provides a linked-list data structure. It has the two constructors, shown here: Linked. List( ) Linked. List(Collection c) 3. The first constructor builds an empty linked list. 4. The second constructor builds a linked list that is initialized with the elements of the collection c. 5. In addition to the methods that it inherits, the Linked. List class defines some useful methods of its own for manipulating and accessing lists. 6. To add elements to the start of the list, use add. First( ); to add elements to the end, use add. Last( ). 7. Their signatures are shown here: void add. First(Object obj) void add. Last(Object obj) Here, obj is the item being added. To obtain the first element, call get. First( ). To retrieve 98 the last element, call get. Last( ). Their signatures are shown here:

Object get. First( ) Object get. Last( ) To remove the first element, use

Object get. First( ) Object get. Last( ) To remove the first element, use remove. First( ); to remove the last element, call remove. Last( ). They are shown here: Object remove. First( ) Object remove. Last( ) import java. util. *; class Linked. List. Demo { public static void main(String args[]) { // create a linked list Linked. List ll = new Linked. List(); // add elements to the linked list ll. add("F"); ll. add("B"); ll. add("D"); ll. add("E"); ll. add("C"); ll. add. Last("Z"); ll. add. First("A"); ll. add(1, "A 2"); 99

System. out. println("Original contents of ll: " + ll); // remove elements from the

System. out. println("Original contents of ll: " + ll); // remove elements from the linked list ll. remove("F"); ll. remove(2); System. out. println("Contents of ll after deletion: “ + ll); // remove first and last elements ll. remove. First(); ll. remove. Last(); System. out. println("ll after deleting first and last: “ + ll); // get and set a value Object val = ll. get(2); ll. set(2, (String) val + " Changed"); System. out. println("ll after change: " + ll); } } 100

The Hash. Set Class 1. Hash. Set extends Abstract. Set and implements the Set

The Hash. Set Class 1. Hash. Set extends Abstract. Set and implements the Set interface. 2. It creates a collection that uses a hash table for storage. 3. As most readers likely know, a hash table stores information by using a mechanism called hashing. 4. In hashing, the informational content of a key is used to determine a unique value, called its hash code. 5. The hash code is then used as the index at which the data associated with the key is stored. 6. The transformation of the key into its hash code is performed automatically—you never see the hash code itself. 7. Also, your code can’t directly index the hash table. 8. The advantage of hashing is that it allows the execution time of basic operations, such as add( ), contains( ), remove( ), and size( ), to remain constant even for large sets. 9. The following constructors are defined: Hash. Set( ) Hash. Set(Collection c) Hash. Set(int capacity) 101

10. The first form constructs a default hash set. 11. The second form initializes

10. The first form constructs a default hash set. 11. The second form initializes the hash set by using the elements of c. 12. The third form initializes the capacity of the hash set to capacity. import java. util. *; public class Collection. Test { public static void main(String [] args) { System. out. println( "Collection Example!n" ); int size; // Create a collection Hash. Set collection = new Hash. Set (); String str 1 = "Yellow", str 2 = "White", str 3 = "Green", str 4 = "Blue"; Iterator iterator; //Adding data in the collection. add(str 1); collection. add(str 2); collection. add(str 3); collection. add(str 4); System. out. print("Collection data: "); //Create a iterator = collection. iterator(); while (iterator. has. Next()) { System. out. print(iterator. next() + " "); } System. out. println(); 102

// Get size of a collection size = collection. size(); if (collection. is. Empty())

// Get size of a collection size = collection. size(); if (collection. is. Empty()) { System. out. println("Collection is empty"); } else { System. out. println( "Collection size: " + size); } System. out. println(); // Remove specific data collection. remove(str 2); System. out. println("After removing [" + str 2 + "]n"); System. out. print("Now collection data: "); iterator = collection. iterator(); while (iterator. has. Next()) { System. out. print(iterator. next() + " "); } System. out. println(); size = collection. size(); System. out. println("Collection size: " + size + "n"); //Collection empty collection. clear(); size = collection. size(); if (collection. is. Empty()) { System. out. println("Collection is empty"); } else { System. out. println( "Collection size: " + size); 103 } }

The Linked. Hash. Set Class 1. Java 2, version 1. 4 adds the Linked.

The Linked. Hash. Set Class 1. Java 2, version 1. 4 adds the Linked. Hash. Set class. 2. This class extends Hash. Set, but adds no members of its own. 3. Linked. Hash. Set maintains a linked list of the entries in the set, in the order in which they were inserted. 4. This allows insertion-order iteration over the set. 5. That is, when cycling through a Linked. Hash. Set using an iterator, the elements will be returned in the order in which they were inserted. 6. This is also the order in which they are contained in the string returned by to. String( ) when called on a Linked. Hash. Set object. 7. To see the effect of Linked. Hash. Set, try substituting Linked. Hash. Set For Hash. Set in the preceding program. 8. The output will be [B, A, D, E, C, F] which is the order in which the elements were inserted. 104

import java. util. Linked. Hash. Set; import java. util. Iterator; public class Hash. Set.

import java. util. Linked. Hash. Set; import java. util. Iterator; public class Hash. Set. Demo { public static void main(String[] args) { //create object of Linked. Hash. Set lhash. Set = new Linked. Hash. Set(); //add elements to Linked. Hash. Set object lhash. Set. add("1"); lhash. Set. add("2"); lhash. Set. add("3"); //get the Iterator itr = lhash. Set. iterator(); System. out. println("Linked. Hash. Set contains : "); while(itr. has. Next()) System. out. println(itr. next()); } } 105

The Tree. Set Class 1. Tree. Set provides an implementation of the Set interface

The Tree. Set Class 1. Tree. Set provides an implementation of the Set interface that uses a tree for storage. 2. Objects are stored in sorted, ascending order. 3. Access and retrieval times are quite fast, which makes Tree. Set an excellent choice when storing large amounts of sorted information that must be found quickly. 4. The following constructors are defined: Tree. Set( ) Tree. Set(Collection c) Tree. Set(Comparator comp) Tree. Set(Sorted. Set ss) 5. The first form constructs an empty tree set that will be sorted in ascending order according to the natural order of its elements. 6. The second form builds a tree set that contains the elements of c. 7. The third form constructs an empty tree set that will be sorted according to the comparator specified by comp. 8. The fourth form builds a tree set that contains the elements of ss. 106

import java. util. *; public class Tree. Set. Demo { public static void main(String[]

import java. util. *; public class Tree. Set. Demo { public static void main(String[] args) { System. out. println("Tree Set Example!n"); Tree. Set tree = new Tree. Set(); tree. add("12"); tree. add("23"); tree. add("34"); tree. add("45"); Iterator iterator; iterator = tree. iterator(); System. out. print("Tree set data: "); //Displaying the Tree set data while (iterator. has. Next()) { System. out. print(iterator. next() + " "); } System. out. println(); 107

//Check impty or not if (tree. is. Empty()) { System. out. print("Tree Set is

//Check impty or not if (tree. is. Empty()) { System. out. print("Tree Set is empty. "); } else { System. out. println("Tree Set size: " + tree. size()); } //Retrieve first data from tree set System. out. println("First data: " + tree. first()); //Retrieve last data from tree set System. out. println("Last data: " + tree. last()); if (tree. remove("23")) { System. out. println("Data is removed from tree set"); } else { System. out. println("Data doesn't exist!"); } 108

System. out. print("Now the tree set contain: "); iterator = tree. iterator(); //Displaying the

System. out. print("Now the tree set contain: "); iterator = tree. iterator(); //Displaying the Tree set data while (iterator. has. Next()) { System. out. print(iterator. next() + " "); } System. out. println(); System. out. println("Now the size of tree set: " + tree. size()); //Remove all tree. clear(); if (tree. is. Empty()) { System. out. print("Tree Set is empty. "); } else { System. out. println("Tree Set size: " + tree. size()); } } } 109

Using an Iterator 1. Before you can access a collection through an iterator, you

Using an Iterator 1. Before you can access a collection through an iterator, you must obtain one. 2. Each of the collection classes provides an iterator( ) method that returns an iterator to the start of the collection. 3. By using this iterator object, you can access each element in the collection, one element at a time. 4. In general, to use an iterator to cycle through the contents of a collection, follow these steps: a. b. c. Obtain an iterator to the start of the collection by calling the collection’s iterator( ) method. Set up a loop that makes a call to has. Next( ). Have the loop iterate as long as has. Next( ) returns true. Within the loop, obtain each element by calling next( ). 110

111

111

import java. util. *; class Iterator. Demo { public static void main(String args[]) {

import java. util. *; class Iterator. Demo { public static void main(String args[]) { // create an array list Array. List al = new Array. List(); // add elements to the array list al. add("C"); al. add("A"); al. add("E"); al. add("B"); al. add("D"); al. add("F"); // use iterator to display contents of al System. out. print("Original contents of al: "); Iterator itr = al. iterator(); while(itr. has. Next()) { Object element = itr. next(); System. out. print(element + " "); } 112

System. out. println(); // modify objects being iterated List. Iterator litr = al. list.

System. out. println(); // modify objects being iterated List. Iterator litr = al. list. Iterator(); while(litr. has. Next()) { Object element = litr. next(); litr. set(element + "+"); } System. out. print("Modified contents of al: "); itr = al. iterator(); while(itr. has. Next()) { Object element = itr. next(); System. out. print(element + " "); } System. out. println(); // now, display the list backwards System. out. print("Modified list backwards: "); while(litr. has. Previous()) { Object element = litr. previous(); System. out. print(element + " "); } System. out. println(); } } 113

Working with Maps 1. A map is an object that stores associations between keys

Working with Maps 1. A map is an object that stores associations between keys and values, or key/value pairs. 2. Given a key, you can find its value. Both keys and values are objects. 3. The keys must be unique, but the values may be duplicated. 4. Some maps can accept a null key and null values, others cannot. The Map Interfaces Interface Map Description Maps unique keys to values. Map. Entry Describes an element (a key/value pair) in a map. This is an inner class of Map. Sorted. Map Extends Map so that the keys are maintained in ascending order. 114

1. 2. 3. 4. 5. The Map interface maps unique keys to values. A

1. 2. 3. 4. 5. The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key. Several methods throw a No. Such. Element. Exception when no items exist in the invoking map. 6. A Class. Cast. Exception is thrown when an object is incompatible with the elements in a map. 7. A Null. Pointer. Exception is thrown if an attempt is made to use a null object and null is not allowed in the map. 8. An Unsupported. Operation. Exception is thrown when an attempt is made to change an unmodifiable map. 9. Maps revolve around two basic operations: get( ) and put( ). 10. To put a value into a map, use put( ), specifying the key and the value. 11. To obtain a value, call get( ), passing the key as an argument. The value is returned. 12. As mentioned earlier, maps are not collections because they do not implement the Collection interface, but you can obtain a collection-view of a map. 13. To do this, you can use the entry. Set( ) method. 14. It returns a Set that contains the elements in the map. 15. To obtain a collection-view of the keys, use key. Set( ). 16. To get a collection-view of the values, use values( ). 17. Collection-views are the means by which maps are integrated into the collections framework. 115

116

116

The Sorted. Map Interface 1. 2. 3. 4. 5. The Sorted. Map interface extends

The Sorted. Map Interface 1. 2. 3. 4. 5. The Sorted. Map interface extends Map. It ensures that the entries are maintained in ascending key order. Several methods throw a No. Such. Element. Exception when no items are in the invoking map. A Class. Cast. Exception is thrown when an object is incompatible with the elements in a map. A Null. Pointer. Exception is thrown if an attempt is made to use a null object when null is not allowed in the map. 6. Sorted maps allow very efficient manipulations of submaps (in other words, a subset of a map). 7. To obtain a submap, use head. Map( ), tail. Map( ), or sub. Map( ). 8. To get the first key in the set, call first. Key( ). To get the last key, use last. Key( ). 117

import java. util. *; public class Sorted. Map. Example { public static void main(String[]

import java. util. *; public class Sorted. Map. Example { public static void main(String[] args) { Sorted. Map map = new Tree. Map(); // Add some elements: map. put("2", "Two"); map. put("1", "One"); map. put("5", "Five"); map. put("4", "Four"); map. put("3", "Three"); // Display the lowest key: System. out. println("The lowest key value is: " + map. first. Key()); // Display the highest key: System. out. println("The highest key value is: " + map. last. Key()); // Display All key value System. out. println("All key value is: n" + map); 118

// Display the head. Map: System. out. println("The head map is: n" + map.

// Display the head. Map: System. out. println("The head map is: n" + map. head. Map("4")); // Display the tail. Map: System. out. println("The tail map is: n" + map. tail. Map("4")); // key. Set method returns a Set view of the keys contained in this map. Iterator iterator = map. key. Set(). iterator(); while (iterator. has. Next()) { Object key = iterator. next(); System. out. println("key : " + key + " value : " + map. get(key)); } } } 119

The Map Classes Several classes provide implementations of the map interfaces. The classes that

The Map Classes Several classes provide implementations of the map interfaces. The classes that can be used for maps are summarized here: Class Description Abstract. Map Implements most of the Map interface. Hash. Map Extends Abstract. Map to use a hash table. Tree. Map Extends Abstract. Map to use a tree. Weak. Hash. Map Extends Abstract. Map to use a hash table with weak keys. Linked. Hash. Map Extends Hash. Map to allow insertion-order iterations. Identity. Hash. Map Extends Abstract. Map and uses reference equality when comparing documents. 120

The Hash. Map Class 1. The Hash. Map class uses a hash table to

The Hash. Map Class 1. The Hash. Map class uses a hash table to implement the Map interface. 2. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets. 3. The following constructors are defined: Hash. Map( ) Hash. Map(Map m) Hash. Map(int capacity) 121

1. 2. 3. 4. 5. 6. 7. The first form constructs a default hash

1. 2. 3. 4. 5. 6. 7. The first form constructs a default hash map. The second form initializes the hash map by using the elements of m. The third form initializes the capacity of the hash map to capacity. Hash. Map implements Map and extends Abstract. Map. It does not add any methods of its own. You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator. import java. util. *; class Hash. Map. Demo { public static void main(String args[]) { // Create a hash map Hash. Map hm = new Hash. Map(); // Put elements to the map hm. put("John Doe", new Double(3434. 34)); hm. put("Tom Smith", new Double(123. 22)); hm. put("Jane Baker", new Double(1378. 00)); hm. put("Todd Hall", new Double(99. 22)); hm. put("Ralph Smith", new Double(-19. 08)); 122

// Get a set of the entries Set set = hm. entry. Set(); //

// Get a set of the entries Set set = hm. entry. Set(); // Get an iterator Iterator i = set. iterator(); // Display elements while(i. has. Next()) { Map. Entry me = (Map. Entry)i. next(); System. out. print(me. get. Key() + ": "); System. out. println(me. get. Value()); } System. out. println(); // Deposit 1000 into John Doe's account double balance = ((Double)hm. get("John Doe")). double. Value(); hm. put("John Doe", new Double(balance + 1000)); System. out. println("John Doe's new balance: " + hm. get("John Doe")); } } 123

The Tree. Map Class 1. The Tree. Map class implements the Map interface by

The Tree. Map Class 1. The Tree. Map class implements the Map interface by using a tree. 2. A Tree. Map provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. 3. You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order. The following Tree. Map constructors are defined: Tree. Map( ) Tree. Map(Comparator comp) Tree. Map(Map m) Tree. Map(Sorted. Map sm) 4. The first form constructs an empty tree map that will be sorted by using the natural order of its keys. 5. The second form constructs an empty tree-based map that will be sorted by using the Comparator comp. 6. The third form initializes a tree map with the entries from m, which will be sorted by using the natural order of the keys. 7. The fourth form initializes a tree map with the entries from sm, which will be sorted in 124 the same order as sm.

import java. util. *; class Tree. Map. Demo { public static void main(String args[])

import java. util. *; class Tree. Map. Demo { public static void main(String args[]) { // Create a tree map Tree. Map tm = new Tree. Map(); // Put elements to the map tm. put("John Doe", new Double(3434. 34)); tm. put("Tom Smith", new Double(123. 22)); tm. put("Jane Baker", new Double(1378. 00)); tm. put("Todd Hall", new Double(99. 22)); tm. put("Ralph Smith", new Double(-19. 08)); // Get a set of the entries Set set = tm. entry. Set(); // Get an iterator Iterator i = set. iterator(); 125

// Display elements while(i. has. Next()) { Map. Entry me = (Map. Entry)i. next();

// Display elements while(i. has. Next()) { Map. Entry me = (Map. Entry)i. next(); System. out. print(me. get. Key() + ": "); System. out. println(me. get. Value()); } System. out. println(); // Deposit 1000 into John Doe's account double balance = ((Double)tm. get("John Doe")). double. Value(); tm. put("John Doe", new Double(balance + 1000)); System. out. println("John Doe's new balance: " + tm. get("John Doe")); } } The Linked. Hash. Map Class 1. Java 2, version 1. 4 adds the Linked. Hash. Map class. 2. This class extends Hash. Map. 3. Linked. Hash. Map maintains a linked list of the entries in the map, in the order in which they were inserted. 4. This allows insertion-order iteration over the map. 5. That is, when iterating a Linked. Hash. Map, the elements will be returned in the order in which they were inserted. 126 6. You can also create a Linked. Hash. Map that returns its elements in the order in which they were last accessed.

Linked. Hash. Map defines the following constructors. Linked. Hash. Map( ) Linked. Hash. Map(Map

Linked. Hash. Map defines the following constructors. Linked. Hash. Map( ) Linked. Hash. Map(Map m) Linked. Hash. Map(int capacity) The first form constructs a default Linked. Hash. Map. The second form initializes the Linked. Hash. Map with the elements from m. The third form initializes the capacity. import java. util. Linked. Hash. Map; public class Linked. Hash. Map. Example { public static void main(String[] args) { //create object of Linked. Hash. Map l. Hash. Map = new Linked. Hash. Map(); l. Hash. Map. put("One", new Integer(1)); l. Hash. Map. put("Two", new Integer(2)); //retrieve value using Object get(Object key) method of Java Linked. Hash. Map class Object obj = l. Hash. Map. get("One"); System. out. println(obj); } } 127

Comparators 1. Both Tree. Set and Tree. Map store elements in sorted order. 2.

Comparators 1. Both Tree. Set and Tree. Map store elements in sorted order. 2. However, it is the comparator that defines precisely what “sorted order” means. 3. By default, these classes store their elements by using what Java refers to as “natural ordering, ” which is usually the ordering that you would expect. (A before B, 1 before 2, and so forth. ) 4. If you want to order elements a different way, then specify a Comparator object when you construct the set or map. 5. Doing so gives you the ability to govern precisely how elements are stored within sorted collections and maps. 6. The Comparator interface defines two methods: compare( ) and equals( ). 7. The compare( ) method, shown here, compares two elements for order: int compare(Object obj 1, Object obj 2) 8. obj 1 and obj 2 are the objects to be compared. 9. This method returns zero if the objects are equal. 10. It returns a positive value if obj 1 is greater than obj 2. 11. Otherwise, a negative value is returned. 12. The method can throw a Class. Cast. Exception if the types of the objects are not compatible for comparison. 13. By overriding compare( ), you can alter the way that objects are ordered. 128 the 14. For example, to sort in reverse order, you can create a comparator that reverses outcome of a comparison.

import java. util. *; // A reverse comparator for strings. class My. Comp implements

import java. util. *; // A reverse comparator for strings. class My. Comp implements Comparator { public int compare(Object a, Object b) { String a. Str, b. Str; a. Str = (String) a; b. Str = (String) b; // reverse the comparison return b. Str. compare. To(a. Str); } } class Comp. Demo { public static void main(String args[]) { // Create a tree set Tree. Set ts = new Tree. Set(new My. Comp()); 129

// Add elements to the tree set ts. add("C"); ts. add("A"); ts. add("B"); ts.

// Add elements to the tree set ts. add("C"); ts. add("A"); ts. add("B"); ts. add("E"); ts. add("F"); ts. add("D"); // Get an iterator Iterator i = ts. iterator(); // Display elements while(i. has. Next()) { Object element = i. next(); System. out. print(element + " "); } System. out. println(); } } 130

The Legacy Classes and Interfaces The legacy classes defined by java. util are shown

The Legacy Classes and Interfaces The legacy classes defined by java. util are shown here: Dictionary Hashtable Properties Stack Vector 1. Vector implements a dynamic array. 2. It is similar to Array. List, but with two differences: Vector is synchronized, and it contains many legacy methods that are not part of the collections framework. 3. With the release of Java 2, Vector was reengineered to extend Abstract. List and implement the List interface, so it now is fully compatible with collections. 4. Here are the Vector constructors: Vector( ) Vector(int size, int incr) Vector(Collection c) 131

5. The first form creates a default vector, which has an initial size of

5. The first form creates a default vector, which has an initial size of 10. 6. The second form creates a vector whose initial capacity is specified by size. 7. The third form creates a vector whose initial capacity is specified by size and whose increment is specified by incr. 8. The increment specifies the number of elements to allocate each time that a vector is resized upward. The fourth form creates a vector that contains the elements of collection c. import java. util. *; class Vector. Demo { public static void main(String args[]) { // initial size is 3, increment is 2 Vector v = new Vector(3, 2); System. out. println("Initial size: " + v. size()); System. out. println("Initial capacity: " + v. capacity()); v. add. Element(new Integer(1)); v. add. Element(new Integer(2)); v. add. Element(new Integer(3)); v. add. Element(new Integer(4)); System. out. println("Capacity after four additions: " + v. capacity()); 132

v. add. Element(new Double(5. 45)); System. out. println("Current capacity: " + v. capacity()); v.

v. add. Element(new Double(5. 45)); System. out. println("Current capacity: " + v. capacity()); v. add. Element(new Double(6. 08)); v. add. Element(new Integer(7)); System. out. println("Current capacity: " + v. capacity()); v. add. Element(new Float(9. 4)); v. add. Element(new Integer(10)); System. out. println("Current capacity: " + v. capacity()); v. add. Element(new Integer(11)); v. add. Element(new Integer(12)); System. out. println("First element: " + (Integer)v. first. Element()); System. out. println("Last element: " + (Integer)v. last. Element()); if(v. contains(new Integer(10))) System. out. println("Vector contains 3. "); // enumerate the elements in the vector. Enumeration v. Enum = v. elements(); System. out. println("n. Elements in vector: "); while(v. Enum. has. More. Elements()) System. out. print(v. Enum. next. Element() + " "); System. out. println(); } } 133

Stack 1. 2. 3. 4. 5. 6. Stack is a subclass of Vector that

Stack 1. 2. 3. 4. 5. 6. Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own. To put an object on the top of the stack, call push( ). To remove and return the top element, call pop( ). An Empty. Stack. Exception is thrown if you call pop( ) when the invoking stack is empty. You can use peek( ) to return, but not remove, the top object. 7. The empty( ) method returns true if nothing is on the stack. 8. The search( ) method determines whether an object exists on the stack, and returns the number of pops that are required to bring it to the top of the stack. import java. util. *; class Stack. Demo { static void showpush(Stack st, int a) { st. push(new Integer(a)); System. out. println("push(" + a + ")"); System. out. println("stack: " + st); } static void showpop(Stack st) { System. out. print("pop -> "); Integer a = (Integer) st. pop(); System. out. println(a); System. out. println("stack: " + st); } 134

public static void main(String args[]) { Stack st = new Stack(); System. out. println("stack:

public static void main(String args[]) { Stack st = new Stack(); System. out. println("stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); try { showpop(st); } catch (Empty. Stack. Exception e) { System. out. println("empty stack"); } } } 135

Dictionary 1. Dictionary is an abstract class that represents a key/value storage repository and

Dictionary 1. Dictionary is an abstract class that represents a key/value storage repository and operates much like Map. 2. Given a key and value, you can store the value in a Dictionary object. 3. Once the value is stored, you can retrieve it by using its key. 4. Thus, like a map, a dictionary can be thought of as a list of key/value pairs. 5. To add a key and a value, use the put( ) method. 6. Use get( ) to retrieve the value of a given key. 7. The keys and values can each be returned as an Enumeration by the keys( ) and elements( ) methods, respectively. 8. The size( ) method returns the number of key/ value pairs stored in a dictionary. 9. is. Empty( ) returns true when the dictionary is empty. 10. You can use the remove( ) method to delete a key/value pair. 136

Hashtable 1. Hashtable was part of the original java. util and is a concrete

Hashtable 1. Hashtable was part of the original java. util and is a concrete implementation of a Dictionary. 2. However, Java 2 reengineered Hashtable so that it also implements the Map interface. 3. Thus, Hashtable is now integrated into the collections framework. 4. It is similar to Hash. Map, but is synchronized. 5. Like Hash. Map, Hashtable stores key/value pairs in a hash table. 6. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. 7. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table. 8. The Hashtable constructors are shown here: Hashtable( ) Hashtable(int size) Hashtable(Map m) The first version is the default constructor. The second version creates a hash table that has an initial size specified by size. The Third version creates a hash table that is initialized with the elements in m. The capacity of the hash table is set to twice the 137 number of elements in m.

import java. util. *; class HTDemo { public static void main(String args[]) { Hashtable

import java. util. *; class HTDemo { public static void main(String args[]) { Hashtable balance = new Hashtable(); Enumeration names; String str; double bal; balance. put("John Doe", new Double(3434. 34)); balance. put("Tom Smith", new Double(123. 22)); balance. put("Jane Baker", new Double(1378. 00)); balance. put("Todd Hall", new Double(99. 22)); balance. put("Ralph Smith", new Double(-19. 08)); // Show all balances in hash table. names = balance. keys(); while(names. has. More. Elements()) { str = (String) names. next. Element(); System. out. println(str + ": " + balance. get(str)); } System. out. println(); // Deposit 1, 000 into John Doe's account bal = ((Double)balance. get("John Doe")). double. Value(); balance. put("John Doe", new Double(bal+1000)); System. out. println("John Doe's new balance: " + balance. get("John Doe")); 138 } }

One important point: like the map classes, Hashtable does not directly support iterators. Thus,

One important point: like the map classes, Hashtable does not directly support iterators. Thus, the preceding program uses an enumeration to display the contents of balance. However, you can obtain set-views of the hash table, which permits the use of iterators. // Use iterators with a Hashtable. import java. util. *; class HTDemo 2 { public static void main(String args[]) { Hashtable balance = new Hashtable(); String str; double bal; balance. put("John Doe", new Double(3434. 34)); balance. put("Tom Smith", new Double(123. 22)); balance. put("Jane Baker", new Double(1378. 00)); balance. put("Todd Hall", new Double(99. 22)); balance. put("Ralph Smith", new Double(-19. 08)); // show all balances in hashtable Set set = balance. key. Set(); // get set-view of keys // get iterator Iterator itr = set. iterator(); 139

while(itr. has. Next()) { str = (String) itr. next(); System. out. println(str + ":

while(itr. has. Next()) { str = (String) itr. next(); System. out. println(str + ": " + balance. get(str)); } System. out. println(); // Deposit 1, 000 into John Doe's account bal = ((Double)balance. get("John Doe")). double. Value(); balance. put("John Doe", new Double(bal+1000)); System. out. println("John Doe's new balance: " + balance. get("John Doe")); } } 140

Properties 1. Properties is a subclass of Hashtable. 2. It is used to maintain

Properties 1. Properties is a subclass of Hashtable. 2. It is used to maintain lists of values in which the key is a String and the value is also a String. 3. The Properties class is used by many other Java classes. 4. For example, it is the type of object returned by System. get. Properties( ) when obtaining environmental values. 5. Properties defines the following instance variable: Properties defaults; This variable holds a default property list associated with a Properties object. Properties defines these constructors: Properties( ) Properties(Properties prop. Default) The first version creates a Properties object that has no default values. The second creates an object that uses prop. Default for its default values. In both cases, the property list is empty. In addition to the methods that Properties inherits from Hashtable, Properties defines the various methods. Properties also contains one deprecated method: save( ). This was replaced by store( ) because save( ) did not handle errors 141 correctly.

142

142

import java. util. *; class Prop. Demo { public static void main(String args[]) {

import java. util. *; class Prop. Demo { public static void main(String args[]) { Properties capitals = new Properties(); Set states; String str; capitals. put("Illinois", "Springfield"); capitals. put("Missouri", "Jefferson City"); capitals. put("Washington", "Olympia"); capitals. put("California", "Sacramento"); capitals. put("Indiana", "Indianapolis"); // Show all states and capitals in hashtable. states = capitals. key. Set(); // get set-view of keys Iterator itr = states. iterator(); while(itr. has. Next()) { str = (String) itr. next(); System. out. println("The capital of " + str + " is " + capitals. get. Property(str) + ". "); } System. out. println(); // look for state not in list -- specify default str = capitals. get. Property("Florida", "Not Found"); System. out. println("The capital of Florida is " + str + ". "); } } 143

APPLET CONTROLS 144

APPLET CONTROLS 144

145

145