java unit4

Upload: arunchinnathambi

Post on 09-Mar-2016

245 views

Category:

Documents


0 download

DESCRIPTION

Thread, IO, Networking

TRANSCRIPT

  • Multi Threading

  • Topics to be Covered:Multi-Threaded ProgrammingInterrupting ThreadThread StatesThread PropertiesThread SynchronizationThread-Safe CollectionsExecutorsSynchronizersThreads and Event-Driven Programming

  • INTRODUCTIONMultithreading extends the idea of multitasking into applications, so you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. Those who are familiar with the modern operation systems such as windows 95 may recognize that they can execute several programs simultaneously. This ability is known as multitasking. In Systems terminology, it is called multithreading.Multithreading is a conceptual programming paradigm where a program is divided into two or more subprograms, which can be implemented at the same time in parallel. In most of our computers, we have only a single processor and therefore, in reality, the processor is doing only one thing at a time. However, the processor switches between the processes so fast that it appears to human beings that all of them are being done simultaneously.Java programs contain only a single sequential flow of control. This is what happens when we execute a normal program. The program begins, runs through a sequence of executions, and finally ends. At any given point of time, there is only one statement under execution.A thread is similar to a program that has a single flow of control. It has a beginning, a body and an end, and executes commands sequentially. In fact, all main programs in our earlier examples can be called single threaded programs.A unique property of Java is its support for multithreading. That is, java enables us to use multiple flows of control in developing programs. Each flow of control may be thought of as in separate tiny program known as thread that runs in parallel to others.

  • SINGLE THREADED PROGRAMclass ABC{-------------------------------------------------------------------------------------------------------------------------}

    BeginningSingle threaded body of executionEnd

  • MULTITHREADED PROGRAM________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________Main ThreadMain method modulestart start start switchingswitchingThread BThread AThread C

  • 7. A program that contains multiple flows of control is known as multithreaded program.8. The above fig. is a java program with four threads, one main and three others. The main thread is actually the main method module, which is designed to create and start the other three threads, namely A, B and C9. Once initiated by the main thread, the threads A, B and C run concurrently and share the resources jointly. The ability of a language to support multithreads is referred to as concurrency.10. Threads in java are subprograms of main application program and share the same memory space, they are known as lightweight threads or lightweight processes..Note:It is important to remember that threads running in parallel does not really mean that they actually run at the same time. Since all the threads are running on a single processor, the flow of execution is shared between the threads.

  • CREATING THREADS1. Creating threads in Java is simple.2. Threads are implemented in the form of objects that contain a method called run().3. The run() method is the heart and soul of any thread. It makes up the entire body of a thread and is the only method in which the threads behavior can be implemented.4. A typical run() would appear as follows:public void run(){------------------------------------------------------}Statements for implementing thread

  • 5. The run() method should be invoked by an object for the concerned thread.6. This can be achieved by creating the thread and initiating it with the help of another thread method called start().7. A new thread can be created in two ways.a. By extending a thread class: Define a class that extends Thread class and override its run() method with the code required by the thread.b. By converting a class to a thread: Define a class that implements Runnable interface. The Runnable interface has only one method, run(), that is to be defined in the method with the code to be executed by the thread.

  • 1. EXTENDING THE THREAD CLASSWe can make our class runnable as a thread by extending the class java.lang.Thread. This gives us access to all the thread methods directly.It includes the following steps:1. Declare the class as extending the Thread class2. Implement the run() method that is responsible for executing the sequence of code that the thread will execute.3. Create a thread object and call the start() method to initiate the thread execution.1. Declaring the classclass MyThread extends Thread{------------------------------------------------------------}

  • 2. Implementing the run() Methodpublic void run(){--------------------------------------------------------------------}Thread Code Here3. Starting New ThreadMyThread aThread = new MyThread();

    aThread.start();//Invoke run() method

  • class A extends Thread{public void run(){for(int i = 1;i
  • class C extends Thread{public void run(){for(int k = 1;k
  • 2. IMPLEMENTING THE RUNNABLE INTERFACEThe Runnable interface declares the run() method that is required for implementing threads in our programs. To do this, we must perform the steps listed below:1. Declare the class an implementing the Runnable interface.2. Implementing the run() method.3. Create a thread by defining an object that is instantiated from the runnable class as the target of the thread.4. Call the threads start() method to run the thread.1. Creating Class:class MyThread implements Runnable{------------------------------------------------------------}

  • 2. Implementing the run() Methodpublic void run(){--------------------------------------------------------------------}Thread Code Here3. Starting New Thread and assign the runnable objectMyThread runnableObj = new MyThread();Thread t = new Thread(runnableObj);

    t.start();//Invoke run() method

  • import java.lang.Thread;

    class X implements Runnable{public void run(){for(int i = 1;i

  • class Z implements Runnable{public void run(){for(int k = 1;k
  • Interrupting Thread:Using sleep() method:Make the thread to sleep for a while. In that particular sleep time the processor executes the other Threads which is ready for an execution.It should thrown a exception called java.lang.InterruptedException, so it must be handled in the program using try-catch.Syntax:Thread.sleep(millisec);class A implements Runnable{public void run(){try{for(int i = 1;i
  • class B extends Thread{public void run(){try{for(int j = 1;j
  • Thread Class and Runnable Interface:To create a new thread, your program will either extend Thread class or implements the Runnable interface.The Thread class defines several methods that help manage threads.

    MethodsMeaninggetName()Obtain a threads namegetPriority()Obtain a threads priorityisAlive()Determine if a thread is still runningjoin()Wait for a thread to terminaterun()Entry point for the threadsleep()Suspend a thread for a period of timestart()Start a thread by calling its run methodcurrentThread()Return the Currently executing thread

  • LIFE CYCLE OF A THREADDuring the life time of a thread, there are many states it can enter. They includeNewborn state

    Runnable state

    Running state

    Blocked state

    Dead state

  • State Transition diagram of a ThreadNewbornBlockedDeadRunningRunnablestart stop stop stop Killed Thread resumenotify suspendsleepwait Idle Thread(Not Runnable)yield Active ThreadNew Thread

  • import java.lang.Thread;

    class A extends Thread{public void run(){for(int i = 1;i

  • class C extends Thread{public void run(){for(int k = 1;k
  • Using isAlive() and join()Two ways exist to determine whether a thread has finished or not. First, you can call isAlive() on the thread. The method is defined by Thread, and its general form is shown here:final boolean isAlive()The isAlive() method returns true if the thread upon which it is called is still running. It returns false otherwise.isAlive()join() While isAlive() is occasionally useful, the method that you will more commonly use to wait for a thread to finish is called join(), shown here:final void join() throws InterruptedExceptionThis method waits until the thread on which it is called terminates. Its name comes from the concept of the calling thread waiting until the specified thread joins it.

  • class A extends Thread{public void run(){for(int i = 1;i
  • class C extends Thread{public void run(){for(int k = 1;k
  • System.out.println("Start Thread A");a.start();System.out.println("Start Thread B");b.start();System.out.println("Start Thread C");c.start();System.out.println("End of main Thread");

    System.out.println("Thread One is Alive: " + a.isAlive());System.out.println("Thread two is Alive: " + b.isAlive());System.out.println("Thread three is Alive: " + c.isAlive());

    try{a.join(); b.join(); c.join();}catch(InterruptedException e){System.out.println("Main Thread Interrupted");}System.out.println("Thread One is Alive: " + a.isAlive());System.out.println("Thread two is Alive: " + b.isAlive());System.out.println("Thread three is Alive: " + c.isAlive());}}

  • THREAD PRIORITYIn java, each thread is assigned a priority, which affects the order in which it is scheduled for running. The threads of the same priority are given equal treatment by the Java scheduler and, therefore, they share the processor of a first come, first serve basis.ThreadName.setPriority(int Number);The intNumber is an integer value to which the threads priority is set. The Thread class defines several priority constants:MIN_PRIORITY = 1NORM_PRIORITY = 5MAX_PRIORITY = 10The intNumber may assume one of these constants or any value between 1 and 10. Note that the default setting is NORM_PRIORITY.

  • import java.lang.Thread;class A extends Thread{public void run(){for(int i = 1;i
  • class C extends Thread{public void run(){for(int k = 1;k
  • yield() method:Thread gives up CPU for other threads ready to runclass MyThread extends Thread {private String name;public MyThread(String name) {this.name = name;}public void run() {for (int i=0;i
  • Race Condition:Two or more threads need to share access to the same data. If two threads have access to the same object and each calls to a method that modifies the state of the object, then the threads depend on the order in which the data were accessed, corrupted objects can result. Such a condition is often called Race Condition.class MyThread extends Thread {private String name;public MyThread(String name) {this.name = name;}public void run() {for (;;) System.out.println(name + ": hello world");}}public class RaceCondition {public static void main(String [] args) {MyThread t1 = new MyThread("thread1");MyThread t2 = new MyThread("thread2");t1.start(); t2.start();}}

  • Synchronization in Threads:When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issue. For example if multiple threads try to write within a same file then they may corrupt the data because one of the threads can overwrite data or while one thread is opening the same file at the same time another thread might be closing the same file.So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept calledmonitors (also called as Semaphore).Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. To enter an objects monitor, just call a method that has been modified with the synchronized keyword.The monitor is used to control the way in which synchronized methods are allowed to access the class or object. When a synchronized method is invoked for a given object, it is said toacquirethe monitor for that object. No other synchronized method may be invoked for that object until the monitor is released. A monitor is automatically released when the method completes its execution and returns. A monitor may also be released when a synchronized method executes certain methods, such aswait(). The thread associated with the currently executing synchronized method becomes not runnable until the wait condition is satisfied and no other method has acquired the object's monitor.

  • While creating Synchronized methods within classes that you create is an easy and effective means of achieving synchronization, it will not work in all cases.

    Syntax:

    access_specifier synchronized void method_name(parameters) {---------// function body}

    class MyThread extends Thread{static String message[] ={ "Chettinad", "College", "of", "Engineering", "and", "Technology."};String id; public MyThread(String id){ this.id = id;} public void run(){ SynchronizedOutput.displayList(id,message);}}

  • class SynchronizedOutput{public static synchronized void displayList(String name,String list[]){try {for(int i=0;i
  • thread1.start();if (thread1.isAlive()) {thread1.join();System.out.println("Thread1 is dead."); }thread2.start();if (thread2.isAlive()) {thread2.join();System.out.println("Thread 2 is dead.");}}catch(InterruptedException e){} } }Output:Thread1: ChettinadThread1: CollegeThread1: ofThread1: EngineeringThread1: andThread1: Technology.Thread1 is dead.Thread2: ChettinadThread2: CollegeThread2: ofThread2: EngineeringThread2: andThread2: Technology.Thread 2 is dead.

  • *APPLETS

  • *What is Applets?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. 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?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.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.Applets cannot read from or write to the files in the local computer.Applets cannot communicate with other servers on the network.Applets cannot run any program from the local computer.Applets are restricted from using libraries from other languages such as C or C++. (Java language supports this feature through native methods.)

  • *Applet ArchitectureAn applet is a window based program. First, applets are event driven. Event driven architecture impacts the design of an applet. An applet resembles a set of interrupt service routines. An applet waits until an event occurs. The AWT notifies the applet about an event by calling an event handler appropriate action and then quickly return control to the AWT. Second, the user initiates interaction with an applet - not the other way around. 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 readLine(). This not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when must respond. For example, when the user clicks a mouse inside the applets window, a mouse clicked event is generated. If the user presses a key while the applets window has input focus, a keypress event is generated. Applets can contain various controls, such as push buttons and check boxes.

  • *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, Javas 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, Javas AWT provides a much cleaner approach that is more quickly mastered.

  • *An Applet Skeleton or Applet Life CycleBornRunningIdleDeadBegin(Load Applet)InitializationDisplayStoppedDestroyedExit of Browserstart( )stop( )start( )paint( )destroy( )End

  • *An Applet Skeleton or Applet Life CycleAll but the the most trivial applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods init( ), start( ), stop( ), and destroy( ) are defined by Applet. Another, paint(), is defined by the AWT Component class. Default implementations for all of these methods are provided. Applets do no need to override those methods they do not use. However, only very simple applets will not need to define all of them.The applet states is:1. Born or initialization state2. Running state3. Idle state4. Dead or destroyed state5. Display state

  • *Initialization StateApplet 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 valuesc. Load images or fontsd. set up colorspublic void init( ){--------------------------------------------------------------------}

    Action

  • *2. Running StateApplets 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

  • *3. Idle or Stopped StateAn 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 the thread. We can achieve by overriding the stop( ) method:public void stop( ){--------------------------------------------------------------------}

    Action

  • *4. Dead StateAn 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 applets 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

  • *5. Display StateApplet 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

  • *import java.awt.*;import java.applet.*;/*

    */public class AppletDemo extends Applet{String msg;public void init(){setBackground(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.drawString(msg,100,100);}}Specified Colors

    Color.black

    Color.blue

    Color.cyan

    Color.darkGray

    Color.gray

    Color.green

    Color.lightGray

    Color.magenta

    Color.orange

    Specified Colors

    10. Color.pink

    11. Color.red

    12. Color.white

    13. Color.yellow

  • *How the applets to be displayed in the Browser

    WELCOME TO cHETTINAD

  • *The HTML APPLET Tag< APPLET [CODEBASE = codebaseURL] CODE = appletFile [ALT = alternateText] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels]>[][]. . . . . . .[HTML Displayed in the absence of Java]

  • *

    ATTRIBUTEMEANINGCODE = AppletFileName.classSpecifies 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 = pixelsHEIGHT = pixelsThese 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, ABSMIDDLE, 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 VALUEThe PARAM tag allows you to specify applet specific arguments in an HTML page. Applets access their attributes with the getParameter() method

  • *Passing Parameters to Appletsimport java.awt.*;import java.applet.*;/*

    */public class ParamDemo extends Applet{String fontName;int fontSize;float leading;boolean active;

    public void start(){String param;

    fontName = getParameter("fontName");if(fontName == null)fontName = "Not Found";

  • *param = getParameter("fontSize");try{if(param != null) //if not foundfontSize = Integer.parseInt(param);elsefontSize = 0;}catch(NumberFormatException e){fontSize = -1;}param = getParameter("leading");try{if(param != null)//if not foundleading = Float.valueOf(param).floatValue();elseleading = 0;}catch(NumberFormatException e){leading = -1;}

  • *param = getParameter("accountEnabled");if(param != null)active = Boolean.valueOf(param).booleanValue();}public void paint(Graphics g){g.drawString("Font name: " + fontName,0,10);g.drawString("Font Size: " + fontSize,0,20);g.drawString("Leading: " + leading, 0,42);g.drawString("Account Active: " + active,0,58);}}

  • *getCodeBase() and getDocumentBase()import java.awt.*;import java.applet.*;import java.net.*;/*

    */public class ParamDemo_2 extends Applet{public void paint(Graphics g){String msg;

    URL url = getCodeBase();msg = "Code Base: " + url.toString();g.drawString(msg,10,20);

    url = getDocumentBase();msg = "Document Base: " + url.toString();g.drawString(msg,10,40);}}

  • *The AudioClip InterfaceThe AudioClip 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. getAudioClip ( ) - After you have loaded an audio clip import java.applet.*; import java.awt.event.*; import java.awt.*;

    /*

    */

    public class SoundExample extends Applet implements MouseListener { AudioClip soundFile1; AudioClip soundFile2;

  • *public void init() { soundFile1 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\ding.wav"); soundFile2 = getAudioClip(getDocumentBase(),"c:\\windows\\media\\start.wav");

    addMouseListener(this); setBackground(Color.yellow); soundFile1.play(); } public void paint(Graphics g) { g.drawString("Click to hear a sound",20,20); } public void mouseClicked(MouseEvent evt) { soundFile2.play(); } public void mousePressed(MouseEvent evt) {} public void mouseReleased(MouseEvent evt) {} public void mouseEntered(MouseEvent evt) {} public void mouseExited(MouseEvent evt) {} }

  • *AppletStub Interface

    The AppletStub 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 isActive () The isActive() method returns the current state of the applet. While an applet is initializing, it is not active, and calls to isActive() return false. The system marks the applet active just prior to calling start(); after this point, calls to isActive() return true.

    public abstract URL getDocumentBase () The getDocumentBase() method returns the complete URL of the HTML file that loaded the applet. This method can be used with the getImage() or getAudioClip() methods to load an image or audio file relative to the HTML file.

    public abstract URL getCodeBase ()

    The getCodeBase() method returns the complete URL of the .class file that contains the applet. This method can be used with the getImage() method or the getAudioClip() method to load an image or audio file relative to the .class file.

  • *public abstract String getParameter (String name) The getParameter() method allows you to get parameters from tags within the tag of the HTML file that loaded the applet. The name parameter of getParameter() must match the name string of the tag; name is case insensitive. The return value of getParameter() 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 tags of the , getParameter() returns null.

    public abstract void appletResize (int width, int height) The appletResize() 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.

  • *The Delegation Event Model1. 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.EventsIn the delegation model, an event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. 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 failure occurs, or an operation is completed.

  • *Event SourcesA source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. Here is the general form:public void addTypeListener(TypeListener el)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 addKeyListener(). 9. The method that registers a mouse motion listener is called addMouseListener(). 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:public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException

  • *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 removeTypeListener(TypeListener 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 removeKeyListener(). 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 Listeners21. 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.

  • *24. The methods that receive and pricess events are defined in a set of interfaces found in java.awt.event. 25. For example, the MouseMotionListener 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.

  • *EVENT CLASSES

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

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

    EVENT CLASSESDESCRIPTIONActionEventGenerated when a button is pressed, a list item is double - clicked, or a menu item is selected.AdjustmentEventGenerated when a scroll bar is manupulatedComponentEventGenerated when a component is hidden, moved, resized, or becomes visible.ContainerEventGenerated when a component is added to or removed from a container.FocusEventGenerated when a component gains or loses keyboard focus.InputEventAbstract super class for all component input event classes.ItemEventGenerated 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.KeyEventGenerated when input is received from the keyboard.MouseEventGenerated when the mouse is dragged, moved, clicked, pressed, or , released; also generated when the mouse enters or exits a component.MouseWheelEventGenerated when the mouse wheel is moved.TextEventGenerated when the value of a text area or text field is changed.WindowsEventGenerated when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.

  • *The ActionEvent ClassAn ActionEvent is generated when a button is pressed, a list item is double - clicked, or a menu item is selected. The ActionEvent class defines 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. In addition. There is an integer constant, ACTION_PERFORMED, which can be used to identify action events. ActionEvent has these three constructors:ActionEvent(Object src, int type, String cmd)

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

    ActionEvent(Object src, int type, String cmd, long when, int modifiers)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.

  • *import java.applet.*;import java.awt.*;import java.awt.event.*;/*

    */public class Button_Setnull extends Applet implements ActionListener{TextField tf1,tf2,tf3;Label l1,l2,l3;Button b1;int x,y,z;

    public void init(){

    setBackground(Color.red);setForeground(Color.green);//setTitle("Addition of Two Numbers");

    setLayout(null);Action Event Example Button Click

  • *l1 = new Label("Enter the A Value");l1.setBounds(0,0,100,25);l2 = new Label("Enter the B Value");l2.setBounds(0,50,100,25);l3 = new Label("Addition of the Two Numbers");l3.setBounds(0,100,170,25);

    tf1 = new TextField(10);tf1.setBounds(200,0,100,25);

    tf2 = new TextField(10);tf2.setBounds(200,50,100,25);

    tf3 = new TextField(10);tf3.setBounds(200,100,100,25);

    b1 = new Button("Click Addition");b1.setBounds(100,150,150,25);

    add(l1);add(tf1);add(l2);add(tf2);add(l3);add(tf3);add(b1);b1.addActionListener(this);}

  • *public void actionPerformed(ActionEvent ae){if(ae.getActionCommand().equals("Click Addition")){

    x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());

    z = x + y;tf3.setText(String.valueOf(z));}}}

  • *import java.applet.*;import java.awt.*;import java.awt.event.*;/*
  • *tf1 = new TextField(10);tf1.setBounds(200,0,100,25);

    tf2 = new TextField(10);tf2.setBounds(200,50,100,25);

    tf3 = new TextField(10);tf3.setBounds(200,100,100,25);

    ls = new List();ch.setBounds(100,150,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(l1);add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ls);

    ls.addActionListener(this);}

  • *public void actionPerformed(ActionEvent ae){if(ls.getSelectedIndex() == 1){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x + y;

    tf3.setText(String.valueOf(z));}if(ls.getSelectedIndex() == 2){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x - y;

    tf3.setText(String.valueOf(z));}

  • *if(ls.getSelectedIndex() == 3){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x * y; tf3.setText(String.valueOf(z));}if(ls.getSelectedIndex() == 4){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x / y; tf3.setText(String.valueOf(z));}if(ls.getSelectedIndex() == 5){tf1.setText(""); tf2.setText(""); tf3.setText("");}if(ls.getSelectedIndex() == 6){int a = ch.getItemCount(); tf3.setText(String.valueOf(a));}if(ls.getSelectedIndex() == 7){tf3.setText(ch.getItem(ch.getSelectedIndex()));}}}

  • *You can obtain the command name for the invoking ActionEvent object by using the getActionCommand() method, shown here:String getActionCommand()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 getModifiers() 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 getModifiers()The AdjustmentEvent ClassAn AdjustementEvent is generated by a scroll bar. There are five types of adjustment events. The AdjustementEvent 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.

  • *In addition, there is an integer constant, ADJUSTMETN_VALUE_CHANGED, that indicates that a change has occurred.Here is one AdjustmentEvent constructor:AdjustmentEvent(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 getAdjustable() method returns the object that generated the event. Its form is shown here:Adjustable getAdjustable()The type of the adjustement event may be obtained by the getAdjustmentType() method. It returns one of the constant defined by AdjustmentEvent. The general form is shown here:int getAdjustmentType()The amount of the adjustement can be obtained from the getValue() method, shown hereint getValue()

  • *import java.applet.*;import java.awt.*;import java.awt.event.*;/*

    */public class Scroll_Setnull extends Applet implements AdjustmentListener{TextField tf1,tf2,tf3;Label l1,l2,l3;Scrollbar sbh,sbv;int x,y,z;public void init(){setBackground(Color.red);setForeground(Color.green);setLayout(null);l1 = new Label("Enter the A Value");l1.setBounds(0,0,100,25);l2 = new Label("Enter the B Value");l2.setBounds(0,50,100,25);l3 = new Label("Compute the Two Numbers");l3.setBounds(0,100,170,25);AdjustmentEvent Example Horizontal and Vertical Scrollbar Changed

  • *tf1 = new TextField(10);tf1.setBounds(200,0,100,25);tf2 = new TextField(10);tf2.setBounds(200,50,100,25);tf3 = new TextField(10);tf3.setBounds(200,100,100,25);

    int height = Integer.parseInt(getParameter("height"));int width = Integer.parseInt(getParameter("width"));

    sbh = new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,height);sbh.setBounds(0,275,975,25);sbv = new Scrollbar(Scrollbar.VERTICAL,0,1,0,width);sbv.setBounds(975,0,25,300);

    sbh.setUnitIncrement(50);sbh.setBlockIncrement(50);sbv.setUnitIncrement(20);sbv.setBlockIncrement(20);

    add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(sbh);add(sbv);sbh.addAdjustmentListener(this);sbv.addAdjustmentListener(this);}

  • *public void adjustmentValueChanged(AdjustmentEvent ae){if(sbh.getValue() == 50){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x + y;

    tf3.setText(String.valueOf(z));}if(sbh.getValue() == 100){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x - y;

    tf3.setText(String.valueOf(z));}

  • *if(sbh.getValue() == 150){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x * y;

    tf3.setText(String.valueOf(z));}if(sbh.getValue() == 200){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x / y;

    tf3.setText(String.valueOf(z));}if(sbh.getValue() == 250){tf1.setText("");tf2.setText("");tf3.setText("");}}}

  • *The ComponentEvent ClassA ComponentEvent is generated when the size, position, or visibility of a component is changed. There are four types of component events. The ComponentEvent 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 visibleComponentEvent has this constructorComponentEvent(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.ComponentEvent is the superclass either directly or indirectly of ContainerEvent, FocusEvent, KeyEvent, MouseEvent, and WindowEvent.The getComponent() method returns the component that generated the event. It is shown here:Component getComponent()

  • *The ContainerEvent ClassA ContainerEvent is generated when a component is added to or removed from a container. There are two types of container events. The ContainerEvent class defines int constants that can be used to identify them: COMPONENT_ADDED and COMPONENET_REMOVED. They indicate that a component has been added or removed form the container.ContainerEvent is a subclass of ComponentEvent and has this constructor:ContainerEvent(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 getCotnainer() method, shown here:Container getContainer()The getChild() method returns a reference to the component that was added to or removed from the container. Its general form is shown here:Component getChild()

  • *A FocusEvent is generated when a component gains or loses input focus. These events are identified by the integer constants FOCUS_GAINED and FOCUS_LOSTFocusEvent is a subclass of ComponentEvent and has threse constructor:FocusEvent(Component src, int type)

    FocusEvent(Component src, int type, boolean temporaryFlag)

    FocusEvent(Component src, int type, boolean temporaryFlag, Component other)Here, src is a reference to the component that generated this event. The type of the event is specified by type. The argument temporaryFlag is set to true if the focus event is temporary. Otherwise, it is set to false. The other component involved in the focus change, called the apposite component, is passed in other. Therefore, if a FOCUS_GAINED event occurred, other will refer to the component that lost focus. Conversely, if a FOCUS_LOST event occurred, other will refer to the component that gains focus.The FocusEvent Class

  • *import java.applet.*;import java.awt.*;import java.awt.event.*;/*

    */public class Focus_Event extends Applet implements FocusListener{TextField tf1,tf2,tf3;public void init(){setBackground(Color.red);setForeground(Color.green);

    tf1 = new TextField(10);tf1.setBounds(200,0,100,25);tf2 = new TextField(10);tf2.setBounds(200,50,100,25);tf3 = new TextField(10);tf3.setBounds(200,100,100,25);add(tf1);add(tf2);add(tf3);tf1.addFocusListener(this);tf2.addFocusListener(this);}FocusEvent Example Focus Gained and Focus Lost in TextBox

  • *public void focusGained(FocusEvent fe){tf2.setText("Focus Gained");}public void focusLost(FocusEvent fe){tf1.setText("Focus Lost");}}

  • *You can determine the other component by calling getOppositeComponent(), shown here.Component getOppositeComponent()The isTemporary() method indicates if this focus change is temporary. Its form is shown here:boolean isTemprorary()The method returns true if the change is temporary. Otherwise, it returns false.The MouseEvent ClassThere are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them:MOUSE_CLICKED-The user clicked the mouse.

    MOUSE_DRAGGED-The user dragged the mouse.

    MOUSE_ENTERED-The mouse entered a component.

    MOUSE_EXITED-The mouse exited from a component.

    MOUSE_MOVED-The mouse moved.

    MOUSE_PRESSED-The mouse was pressed.

    MOUSE_RELEASED-The mouse was released.

    MOUSE_WHEEL-The mouse wheel was moved.

  • *MouseEvent is a subclass of InputEvent. Here is one of its constructor.MouseEvent(Component src, int type, long when, int modifiers, int x,int y, int clicks, boolean triggersPopupHere, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers aregument indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The triggersPopup flag indicates if this event causes a pop up menu to appear on this platform

    MethodsDescriptionint getX() and int getY()These retrun the X and Y coordinates of the mouse when the event occuredPoint getPoint()It returns a Point object that contains the X, Y coordinates in its integer members.getClickCount()The methods obtains the number of mouse clicks for this eventisPopupTrigger()This method tests if this event causes a pop up menu to appear on this platform

  • *import java.awt.*;import java.awt.event.*;import java.applet.*;/*

    */public class Mouse extends Applet implements MouseListener,MouseMotionListener{int X=0,Y=20;String msg="MouseEvents";public void init(){addMouseListener(this);addMouseMotionListener(this);setBackground(Color.black);setForeground(Color.red);}public void mouseEntered(MouseEvent m){setBackground(Color.magenta);showStatus("Mouse Entered");repaint();}public void mouseExited(MouseEvent m){setBackground(Color.black);showStatus("Mouse Exited");repaint();}MouseEvent Example in Mouse

  • *public void mousePressed(MouseEvent m){X=10;Y=20;msg="CCET";setBackground(Color.green);repaint();}public void mouseReleased(MouseEvent m){X=10;Y=20;msg="Engineering";setBackground(Color.blue);repaint();}public void mouseMoved(MouseEvent m){X=m.getX();Y=m.getY();msg="College";setBackground(Color.white);showStatus("Mouse Moved");repaint();}

  • *public void mouseDragged(MouseEvent m){msg="CSE";setBackground(Color.yellow);showStatus("Mouse Moved"+m.getX()+" "+m.getY());repaint();}public void mouseClicked(MouseEvent m){msg="Students";setBackground(Color.pink);showStatus("Mouse Clicked");repaint();}public void paint(Graphics g){g.drawString(msg,X,Y);}}

  • *The MouseWheelEvent ClassThe MouseWheelEvent 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. MouseWheelEvent defines these two integer constants.WHEEL_BLOCK_SCROLL- A page up or page down scroll event occurred

    WHEEL_UNIT_SCROLL-A line up or line down scroll event occuredMouseWheelEvent defines the following constructor:MouseWheelEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup, int scrollHow, 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 scrollHow value must be either is passes in amount. The count parameter indicates the number of roational units that the wheel moved.

  • *The InputEvent ClassThe abstract class InputEvent is a subclass of ComponentEvent and is the superclass for component input events. Its subclasses are keyEvent and MouseEvent.InputEvent defines several integer constants that represent any modifiers, such as the control key being pressed, that might be assocated with the event. Originally, the InputEvent class defined the following eight values to represent the modifiers.ALT_MASKBUTTON2_MASKMETA_MASK

    BUTTON3_MASKSHIFT_MASK

    BUTTON1_MASKCTRL_MASK

    MethodsDescriptionint getWheelRotation()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 getScrollType()It returns either WHEEL_UNIT_SCORLL or WHEEL_BLOCK_SCROLLint getScrollAmount()If the scroll type is WHEEL_UNIT_SCROLL you can obtain the number of units to scroll by calling getScrollAmount().

  • *4. However, because of possible conflicts between the modifiers used by keyboard events and mouse events, and other issues, Java2 version 1.4, added the following extended modifier values.ALT_DOWN_MASKBUTTON2_DOWN_MASKMETA_DOWN_MASK

    BUTTON3_DOWN_MASKSHIFT_DOWN_MASK

    BUTTON1_DOWN_MASKCTRL_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 isAltDown(), isAltGraphDown(), isControlDown(), isMetaDown(), and isShiftDown() methods. 7. The forms of these methods are shown here:boolean isAltDown()boolean isAltGraphDown()boolean isControlDown()boolean isMetaDown()boolean isShiftDown()

  • *You can obtain a value that contains all of the original modifer flags by calling the getModifiers() method. It is shown here:int getModifiers()You can obtain the extended modifiers by called getModifiersEx(), which is shown here:int getModifiersEx()The ItemEvent ClassAn ItemEvent is generated when a check box or a list item is clicked or when a checkable menu item is selected or deselected. 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 itemIn addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED, that signifies a change of state.ItemEvent(ItemSelectable src, int type, Object entry, int state)

  • *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 getItem() method can be used to obtain a reference to the item that generated an event. Its signature is shown here:Object getItem()8. The getItemSelectable() method can be used to obtain a reference to the ItemSelectable object that generated an event. Its general form shown here:itemSelectable getItemSelectable()9. Lists and choices are examples of user interface elements that implement the ItemSelectable interface.10. The getStateChange() method returns the state change for the event. It is shown here:int getStateChange()

  • *import java.applet.*;import java.awt.*;import java.awt.event.*;/*

    */public class Checkbox_Setnull extends Applet implements ItemListener{TextField tf1,tf2,tf3;Label l1,l2,l3;Checkbox ch1,ch2,ch3,ch4,ch5;int x,y,z;public void init(){setBackground(Color.red);setForeground(Color.green);setLayout(null);

    l1 = new Label("Enter the A Value");l1.setBounds(0,0,100,25);l2 = new Label("Enter the B Value");l2.setBounds(0,50,100,25);l3 = new Label("Addition of the Two Numbers");l3.setBounds(0,100,170,25);ItemEvent Example in Checkbox

  • *tf1 = new TextField(10);tf1.setBounds(200,0,100,25);tf2 = new TextField(10);tf2.setBounds(200,50,100,25);tf3 = new TextField(10);tf3.setBounds(200,100,100,25);ch1 = new Checkbox("Addition");ch1.setBounds(100,150,150,25);ch2 = new Checkbox("Subtraction");ch2.setBounds(250,150,150,25);ch3 = new Checkbox("Multiplication");ch3.setBounds(400,150,150,25);ch4 = new Checkbox("Division");ch4.setBounds(550,150,150,25);ch5 = new Checkbox("Clear");ch5.setBounds(700,150,150,25);

    add(l1);add(tf1);add(l2);add(tf2);add(l3);add(tf3);add(ch1);add(ch2); add(ch3); add(ch4); add(ch5);

    ch1.addItemListener(this); ch2.addItemListener(this);ch3.addItemListener(this); ch4.addItemListener(this);ch5.addItemListener(this);}

  • *public void itemStateChanged(ItemEvent ie){if(ch1.getState()==true){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());

    z = x + y;

    tf3.setText(String.valueOf(z));}if(ch2.getState()==true){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());

    z = x - y;

    tf3.setText(String.valueOf(z));}

  • *if(ch3.getState()==true){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());

    z = x * y;

    tf3.setText(String.valueOf(z));}if(ch4.getState()==true){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());

    z = x / y;

    tf3.setText(String.valueOf(z));}if(ch5.getState()==true){tf1.setText("");tf2.setText("");tf3.setText("");}}}

  • *import java.applet.*;import java.awt.*;import java.awt.event.*;/*

    */public class Checkboxgroup_Setnull extends Applet implements ItemListener{TextField tf1,tf2,tf3;Label l1,l2,l3;Checkbox ch1,ch2,ch3,ch4,ch5;CheckboxGroup cbg;int x,y,z;public void init(){setBackground(Color.red);setForeground(Color.green);setLayout(null);cbg = new CheckboxGroup();l1 = new Label("Enter the A Value");l1.setBounds(0,0,100,25);l2 = new Label("Enter the B Value");l2.setBounds(0,50,100,25);l3 = new Label("Compute the Two Numbers");l3.setBounds(0,100,170,25);ItemEvent Example in CheckboxGroup

  • *tf1 = new TextField(10);tf1.setBounds(200,0,100,25);tf2 = new TextField(10);tf2.setBounds(200,50,100,25);tf3 = new TextField(10);tf3.setBounds(200,100,100,25);

    ch1 = new Checkbox("Addition",cbg,false);ch1.setBounds(100,150,150,25);ch2 = new Checkbox("Subtraction",cbg,false);ch2.setBounds(250,150,150,25);ch3 = new Checkbox("Multiplication",cbg,false);ch3.setBounds(400,150,150,25);ch4 = new Checkbox("Division",cbg,false);ch4.setBounds(550,150,150,25);ch5 = new Checkbox("Clear",cbg,false);ch5.setBounds(700,150,150,25);

    add(l1);add(tf1);add(l2);add(tf2);add(l3);add(tf3);add(ch1);add(ch2); add(ch3); add(ch4); add(ch5);

    ch1.addItemListener(this); ch2.addItemListener(this);ch3.addItemListener(this); ch4.addItemListener(this);ch5.addItemListener(this);}

  • *public void itemStateChanged(ItemEvent ie){if(ch1.getState()==true){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());

    z = x + y;

    tf3.setText(String.valueOf(z));l3.setVisible(true);tf3.setVisible(true);}if(ch2.getState()==true){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());

    z = x - y;

    tf3.setText(String.valueOf(z));}

  • *if(ch3.getState()==true){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());

    z = x * y;

    tf3.setText(String.valueOf(z));}if(ch4.getState()==true){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());

    z = x / y;

    tf3.setText(String.valueOf(z));}if(ch5.getState()==true){tf1.setText(""); tf2.setText(""); tf3.setText("");}}}

  • *import java.applet.*;import java.awt.*;import java.awt.event.*;/*

    */public class Choicebox_Setnull extends Applet implements ItemListener{TextField tf1,tf2,tf3;Label l1,l2,l3;Choice ch;int x,y,z;public void init(){setBackground(Color.red);setForeground(Color.green);setLayout(null);l1 = new Label("Enter the A Value");l1.setBounds(0,0,100,25);l2 = new Label("Enter the B Value");l2.setBounds(0,50,100,25);l3 = new Label("Compute the Two Numbers");l3.setBounds(0,100,170,25);ItemEvent Example in Choice Box

  • *tf1 = new TextField(10);tf1.setBounds(200,0,100,25);

    tf2 = new TextField(10);tf2.setBounds(200,50,100,25);

    tf3 = new TextField(10);tf3.setBounds(200,100,100,25);

    ch = new Choice();ch.setBounds(100,150,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(l1);add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(ch);

    ch.addItemListener(this);}

  • *public void itemStateChanged(ItemEvent ie){if(ch.getSelectedIndex() == 1){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x + y;

    tf3.setText(String.valueOf(z));}if(ch.getSelectedIndex() == 2){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x - y;

    tf3.setText(String.valueOf(z));}

  • *if(ch.getSelectedIndex() == 3){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x * y; tf3.setText(String.valueOf(z));}if(ch.getSelectedIndex() == 4){x = Integer.parseInt(tf1.getText());y = Integer.parseInt(tf2.getText());z = x / y; tf3.setText(String.valueOf(z));}if(ch.getSelectedIndex() == 5){tf1.setText(""); tf2.setText(""); tf3.setText("");}if(ch.getSelectedIndex() == 6){int a = ch.getItemCount(); tf3.setText(String.valueOf(a));}if(ch.getSelectedIndex() == 7){tf3.setText(ch.getItem(ch.getSelectedIndex()));}}}

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

    VK_DOWNVK_LEFTVK_RIGHTVK_PAGE_DOWN

    VK_PAGE_UPVK_SHIFTVK_ALTVK_CONTROL

  • *9. The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or alt. KeyEvent is a subclass of InputEvent. 10. Here are two of its constructors:KeyEvent(Component src, int type, long when, int modifiers, int code)

    KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)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 KeyEvent class defines several methods, but the most commonly used ones are getKeyChar(), which returns the character that was entered, and getKeyCode(), which returns the key code.

  • *//the key event handlesimport java.awt.*;import java.awt.event.*;import java.applet.*;/*

    */public class Key_Event extends Applet implements KeyListener{String msg="";int x=10,y=20;public void init(){addKeyListener(this);}public void keyPressed(KeyEvent ke){showStatus("Key Down");}public void keyReleased(KeyEvent ke){showStatus("Key Up");}public void keyTyped(KeyEvent ke){msg+=ke.getKeyChar();repaint();}public void paint(Graphics g){g.drawString(msg,x,y);}}KeyEvent Example in Keyboard

  • *Their general forms are shown here:char getKeyChar()

    int getKeyCode()If not valid character is available, then getKeyChar() returns CHAR_UNDEFINED. When a KEY_TYPED event occurs, getKeyCode() returns VK_UNDEFINEDThe TextEvent ClassInstances of this class describe text events. These are generated by text fields and text areas when characters are entered by a user or program. TextEvent defines the integer constant TEXT_VALUE_CHANGED. The one constructor for this class is shown here:TextEvent(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.

  • *import java.applet.*;import java.awt.*;import java.awt.event.*;/*

    */public class Text_Event extends Applet implements TextListener{TextField tf1,tf2,tf3;public void init(){setBackground(Color.red);setForeground(Color.green);tf1 = new TextField(10);tf1.setBounds(200,0,100,25);tf2 = new TextField(10);tf2.setBounds(200,50,100,25);tf3 = new TextField(10);tf3.setBounds(200,100,100,25);add(tf1);add(tf2);add(tf3);tf1.addTextListener(this);tf2.addTextListener(this);}public void textValueChanged(TextEvent te){tf3.setText(tf1.getText());}}TextEvent Example in Textbox

  • *The WindowEvent ClassThere are ten types of window events. The WindowEvent 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.

  • *WindowEvent is a subclass of ComponentEvent. It defines the following constructor.WindowEvent(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 getWindow(). It returns the Window object that generated the event. Its general form is shown here:Window getWindow()

  • *

    Event ClassesEvent Listener InterfacesEvent Listener Interfaces MethodsActionEventActionListenervoid actionPerformed(ActionEvent ae)AdjustmentEventAdjustmentListenervoid adjustmentValueChanged(AdjustmentEvent ae)ComponentEventComponentListenervoid componentResized(ComponentEvent ce)void componentMoved(ComponentEvent ce)void componentShown(ComponentEvent ce)void componentHidden(CommonentEvent ce)ContainerEventContainerListenervoid componentAdded(ContainerEvent ce)void componentRemoved(ContainterEvent ce)FocusEventFocusListenervoid focusGained(FocusEvent fe)void focusLost(FocusEvent fe)InputEventItemEventItemListenervoid itemStateChanged(ItemEvent ie)KeyEventKeyListenerVoid keyPressed(KeyEvent ke)Void keyReleased(KeyEvent ke)Void KeyTyped(KeyEvent ke)MouseEventMouseListener

    MouseMotionListenervoid mouseClicked(MouseEvent me)void mouseEntered(MouseEvent me)void mouseExited(MouseEvent me)void mousePressed(MouseEvent me)void mouseReleased(MouseEvent me)

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

  • *

    Event ClassesEvent Listener InterfacesEvent Listener Interfaces MethodsMouseWheelEventMouseWheelListenervoid mouseWheelMoved(MouseWheelEvent mwe)TextEventTextListenervoid textChanged(TextEvent te)WindowEventWindowsListener

    WindowFocusListenervoid windowActivated(WindowEvent we)void windowClosed(WindowEvent we)void windowClosing(WindowEvent we)void windowDeactivated(WindowEvent we)void windowDeiconified(WindowEvent we)void windowIconified(WindowEvent we)void windowOpened(WindowEvent we)

    Void windowGainedFocus(WindowEvent we)Void windowLostFocus(WindowEvent we)

  • *Sources of Events

    Event SourceDescriptionButtonGenerates action events when the button is pressed.CheckboxGenerates item event s when the check box is selected or deselected.ChoiceGenerates item event s when the choice is changed.ListGenerates action event s when an item is double clicked; generates item event when an item is selected or deselected.Menu ItemGenerates action event swhen a menu item is selected; generates item events when a checkable menu item is selected or deselected.ScrollbarGenerates adjustment event when the scroll bar is manipulated.Text componentsGenerates text events when the user enters a character.WindowGenerated window events when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.

  • *APPLET CONTROLS

  • *

  • NetworkingComputer on Internet communicate to each other using any one of the following: Transmission Control Protocol(TCP) User Datagram Protocol(UDP)Every Host in the network is identified by using unique ID - Internet protocol (IP) addressesEvery host on Internet has a unique IP address 143.89.40.46, 203.184.197.198 203.184.197.196, 203.184.197.197, 127.0.0. More convenient to refer to using hostname stringcse.ust.hk, tom.com, localhostOne hostname can correspond to multiple internet addresses:www.yahoo.com: 66.218.70.49; 66.218.70.50; 66.218.71.80; 66.218.71.84; Domain Naming Service (DNS) maps names to numbers

    *

  • NetworkingSocketA socket is bound to a port number so that the TCP layer can identify the correct application for dataPortsMany different services can be running on the host. A port identifies a service within a hostMany standard port numbers are pre-assigned time of day 13, ftp 21, telnet 23, smtp 25, http 80IP address + port number = "phone number for service

    protocols : rules that facilitate communications between machinesExamples: HTTP: HyperText Transfer Protocol FTP: File Transfer Protocol SMTP: Simple Message Transfer Protocol TCP: Transmission Control ProtocolUDP: User Datagram Protocol, good for, e.g., video delivery)

    Protocols are standardized and documented. So machines can reliably work with one another

    *

  • NetworkingClient-Server interactionCommunication between hosts is two-way, but usually the two hosts take different roles

    ServerServer waits for client to make requestServer registered on a known port with the host ("public phone number")Usually running in endless loopListens for incoming client connectionsServer offers shared resource (information,database, files, printer, compute power) to clients

    ClientClient "calls" server to start a conversationClient making calls uses hostname/IP address and port numberSends request and waits for responseStandard services always running ftp, http, smtp, etc. server running on host using expected port

    *

  • Networking Socket level Programmingjava.net.Socket is an abstraction of a bi-directional communication channel between hostsSend and receive data using streams

    *

  • *Client/Server Communications

    Server Host

    Server socket on port 8000

    SeverSocket server =

    new ServerSocket(8000);

    A client socket

    Socket socket =

    server.accept()

    Client socket

    Socket socket =

    new Socket(host, 8000)

    I/O Stream

    Client Host

  • Networking Communication ProtocolsTCP - Transmission Control ProtocolReliable - When TCP segments, the smallest unit of TCP transmissions, are lost or corrupted, the TCP implementation will detect this and retransmit necessary segmentsConnection-oriented - TCP sets up a connection before transmission of any dataContinuous Stream - TCP provides a communication medium that allows for an arbitrary number of bytes to be sent and received smoothly

    UDP User Datagram ProtocolUnreliable - UDP has no mechanism for detecting errors nor for retransmission of lost dataConnectionless - UDP does not negotiate a connection before transmission of dataMessage-oriented - UDP allows application to send self-contained messages within UDP datagrams*

  • NetworkingOccasionally, you would like to know who is connecting to the server. You can use the InetAddress class to find the client's host name and IP address. The InetAddress class models an IP address. You can use the statement shown below to create an instance of InetAddress for the client on a socket.

    InetAddress inetAddress = socket.getInetAddress();

    Next, you can display the client's host name and IP address, as follows:

    System.out.println("Client's host name is " + inetAddress.getHostName());System.out.println("Client's IP Address is " + inetAddress.getHostAddress());

    *

  • Networking - Inside Java.netThe Socket Server Socket DatagramSocket and MulticastSocket

    Classes implement client and server sockets for connection-oriented and connectionless communication.*

  • UDP Clientimport java.net.*;import java.io.*;

    class UDPClient{ publicstaticvoid main(String args[]) throws Exception { DatagramSocket dsoc=new DatagramSocket(24); byte buff[]=newbyte[1024]; DatagramPacket dpack=new DatagramPacket(buff,buff.length); dsoc.receive(dpack); System.out.println(new String(dpack.getData())); }}

    *

  • UDP Serverimport java.net.*;import java.io.*;import java.util.*;

    class UDPServer{ publicstaticvoid main(String args[]) throws Exception { DatagramSocket dsoc=new DatagramSocket(5217); InetAddress host=InetAddress.getLocalHost(); String str=(new Date()).toString(); byte buf[]=str.getBytes(); dsoc.send(new DatagramPacket(buf,buf.length,host,24)); dsoc.close(); }}*

  • TCP - Simple-Client ExampleThis client tries to connect to a server (coming soon) and port given on the command line, then sends some output to the server, and finally receives some input which is printed on the screen.

  • TCP - Simple-Server ExampleThe server creates a server socket that listen on the port given on the command line. It then enters infinite loop doing the following: when a connection with a client is established it reads some input from the client (terminated with a 0 byte), sends back the message Simon says: plus the input received, and closes the connection.

    ***