You are on page 1of 15

Java Event Handling Model

In Java, an event is an object which specifies the change of state in the source. It is generated
whenever an action takes place like a mouse button is clicked or text is modified. Java’s AWT
(Abstract Window Toolkit) is responsible for communicating these actions between the program
and the user. Java packages such as java. util, java. awt, java. awt. event and javax. swing
support event handling mechanism.

When an action takes place, an event is generated. The generated event and all the information
about it such as time of its occurrence, type of event, etc. are sent to the appropriate event
handling code provided within the program. This code determines how the allocated event will
be handled so that an appropriate response can be sent to the user.

The working of an event-driven program is governed by its underlying event-handling model.


Till now two models have been introduced in Java for receiving and processing events. The
event handling mechanisms of these models differ a lot from each other. The two event handling
models are “Java 1.0 Event model” and “Delegation event model”.

1) Java 1.0 Event Model

The Java 1.0 Event model for event processing was based on the concept of containment. In this
approach, when a user-initiated event is generated it is first sent to the component in which the
event has occurred. But in case the event is not handled at this component, it is automatically
propagated to the container of that component. This process is continued until the event .is
processed or it reaches the root of the containment hierarchy.

For example, as shown in the Figure, Button is contained in the Panel which itself is contained
within the Frame. When the mouse is clicked on Button, an event is generated which is first sent
to the Button. If it is not handled by it then this event is forwarded to the Panel and if it cannot
handle the event, it is further sent to the Frame. Frame being the root of the given hierarchy
processes this event. So the event is forwarded up the containment hierarchy until it is handled
by a component.
The major drawback in this approach is that events could be handled by the component that
generated it or by the container of that component. Another problem is that events are frequently
sent to those components that cannot process them, thus wasting a lot of CPU cycles.

2) Delegation Event Model

The advanced versions of Java ruled out the limitations of Java 1.0 event model. This model is
referred to as the Delegation Event Model which defines a logical approach to handle events. It
is based on the concept of source and listener. A source generates an event and sends it to one or
more listeners. On receiving the event, listener processes the event and returns it. The notable
feature of this model is that the source has a registered list of listeners which will receive the
events as they occur. Only the listeners that have been registered actually receive the notification
when a specific event is generated.

For example, as shown in Figure, when the mouse is clicked on Button, an event is generated. If
the Button has a registered listener to handle the event, this event is sent to Button, processed and
the output is returned to the user. However, if it has no registered listener the event will not be
propagated upwards to Panel or Frame.

• Event source: An event source is an object that generates a particular kind of event. An event
is generated when the internal state of the event source is changed. A source may generate more
than one type of event. Every source must register a list of listeners that are interested to receive
the notifications regarding the type of event. Event source provides methods to add or remove
listeners.

The general form of method to register (add) a listener is:


public void addTypeListener(TypeListener eventlistener)
Similarly, the general form of method to unregister (remove) a listener is:
public void removeTypeListener(TypeListener eventlistener)
where,
Type is the name of the event
eventlistener is a reference to the event listener
• Event listener: An event listener is an object which receives notification when an event occurs.
As already mentioned, only registered listeners can receive notifications from sources about
specific types of events. The role of event listener is to receive these notifications and process
them.

Java Adapter Classes with Example

The listener class that implements the Listener interface must provide bodies for all of the
methods of that interface. It is not a problem for all the semantic listener interfaces such as
ActionEvent, ItemEvent, TextEvent, AdapterEvent as each of them declares only one method.
However, for all the low-level listener interfaces where each interface contains multiple methods,
implementing each method can be somewhat tedious, especially when we have to define
methods in which we are not interested. For example: Suppose we are interested in setting up
only one listener interface method windowClosing() of the WindowListener interface that causes
the program to terminate. In that case, we would not only need to provide code for
windowClosing() method but also need to write empty bodies for the other methods available in
the WindowListener interface.

class WindowEventFrame extends Frame implements WindowListener {


   ..................
    public void windowClosing(WindowEvent e){
        System.exit(0);
    }
public void windowOpened(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowlconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
..................
}

To avoid this unnecessary code, the java.awt.event package provides adapter classes for various
event-listener types. The event listener interfaces that contain more than one method have a
corresponding event adapter class that implements the interface and defines each method in the
interface with an empty method body. For example, the adapter class for the WindowListener
interface is WindowAdapter.

The following table lists some of the listener interfaces and their corresponding adapter classes.

Now instead of implementing an event listener interface, you can extend the corresponding event
adapter class and define only those methods in which you are interested. For example, The
following code segment shows that a class MyWindowAdapter extends WindowAdapter and
implements the windowClosing() method.
class MyWindowAdapter extends WindowAdapter {
    public void windowClosing(WindowEvent e){
       System.exit(0);
    }
}

This class can be registered using the following statement,


this.addWindowListener(new MyWindowAdapter());
However, if the class is a subclass of a Frame or Applet class, then you cannot define the class as
a subclass of WindowAdapter. In such a case, you can use inner classes. So the preceding
MyWindowAdapter class and addWindowListener statement replaced with the following
statements,

this.addWindowListener( new WindowAdapter() {


     public void windowClosing(WindowEvent e) {
         System.exit(0);
     }
}) ;

You can read this syntax as defining an anonymous inner class as a subclass ofWindowAdapter,
create an instance of this inner class and use this instance as an argument to the
addWindowListener () method.
The following program demonstrates how the adapter class is created and used.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class AdapterExample extends JFrame
{
       AdapterExample()
       {
          this.addWindowListener( new WindowAdapter() {
          public void windowClosing(WindowEvent e)
                           {
                              System.exit(0);
                           }
                           });
       }
}
    class AdapterClassJavaExample
{
      public static void main(String [] args)
      {
        AdapterExample frame = new AdapterExample();
        frame.setTitle("Adapter Class Java Example");
        frame.setBounds(100,200,200,200);
        frame.setVisible(true);
      }
}

Inner Classes In Java

In Java, it is possible to nest the classes, that is, writing classes inside classes. Such type of
structure is also known as nested classes or inner classes.

Java Inner Class

A class within another class is called a nested class or an inner class. In other words, the inner
class is a member of a class just as a class has a member as variables and methods; it can also
have another class as its member.

Such class, which has other classes as its members, is called a top-level class or outer class. A
top-level class may contain any number of inner classes.

Need for Inner Class in Java

Why to use an inner class rather than using separate classes? The following points will help you
understand the purpose of using inner class along with its importance:

 It helps in the logical grouping of classes that belong together:

Suppose there is a class that is useful only to a single class, then we can logically embed it in that
class and keep the two classes together. It will help their package to be more streamlined.

 It helps to increase the encapsulation:

Suppose there are two top-level or outer classes, named C1 and C2, where class C2 needs to
access the private members of the class C1. By nesting class C2 within the class C1, members of
C1 can be declared as private, and C2 can access them.

Also, we can protect C2 from the outside world. Eventually, this will lead to strong
encapsulation and security.

 It helps to increase the readability and maintainability of the code:

Placing inner classes within the top-level classes helps to put the code closer to where it is going
to be used.

Syntax of writing inner class:

Following is the syntax to write an inner class or nested class. Here, the class OuterClassDemo is
the outer class or the top-level class and the class InnerClassDemo is the nested or inner class.
class OuterClassDemo
{
//code of the outer class
class InnerClassDemo
{
//code of inner class
}
}
Types of Inner Classes in Java

There are four types of inner classes:

1. Nested Inner Class


2. Static Inner Class
3. Method Local Inner Class
4. Anonymous Inner Class

1. Nested Inner Class

Nested Inner class is an inner class that can access other instance variables of the outer class,
even if they are declared as private. We can use any access modifier for the nested inner class –
public, private, protected, or default.

package com.mypack.innerclass;
public class JavaOuterClass
{
// private variable of the outer class
private int value = 30;
// inner class
class JavaInnerClass
{
// public variable of the inner class
public int getValue()
{
System.out.println("This is the getValue method of the inner class:");
return value;
}
} //inner class end here
public static void main(String args[])
{
//Creating object of outer class
JavaOuterClass outer = new JavaOuterClass();
// Creating object of inner class
JavaOuterClass.JavaInnerClass inner = outer.new JavaInnerClass();
System.out.println("Value:" inner.getValue());
}
}

Output:

This is the getValue method of the inner class:


Value: 30

2. Method Local Inner class

Method Local Inner Class allows us to declare a class inside a method body that will be of a
local type. The scope of the inner class is restricted within the method, similar to the local
variables. We can initialize a local inner class only inside the method where the inner class is
defined. We cannot declare Method Local Class as private, protected, static and transient but we
can declare it as abstract and final, but not both at the same time.

package com.mypack.innerclass;
//outer class
public class OuterClass
{
void outerMethod()
{
System.out.println("Inside outer method");
//inner class inside a method of outer class
class InnerClass
{
void innerMethod()
{
System.out.println("Inside inner method");
}
} //inner class ends here
//initializing object of inner class inside the method
InnerClass innerObj = new InnerClass();
innerObj.innerMethod();
} //method ends here
public static void main(String[] args)
{
OuterClass outerObj = new OuterClass();
outerObj.outerMethod();
}
}

Output:

Inside outer method


Inside inner method
Note: A Method Local class cannot access a local variable from the outer class. To access the
local variable from the outer class, we must define it as final.

For example, the below code generates an error if we do not declare the variable as final:

package com.techvidvan.innerclass;
//outer class
public class OuterClass
{
void outerMethod()
{
final int var = 60; //declaring variable as final
System.out.println("Inside outer method");
//inner class inside a method of outer class
class InnerClass
{
void innerMethod()
{
System.out.println("\nInside inner method");
System.out.println("Value of variable is: "+var);
}
}//inner class ends here
//initializing object of inner class inside the method
InnerClass innerObj = new InnerClass();
innerObj.innerMethod();
} //method ends here
public static void main(String[] args)
{
OuterClass outerObj = new OuterClass();
outerObj.outerMethod();
}
}

Output:

Inside outer method


Inside inner method
Value of variable is: 60
3. Static Inner class

A static inner class acts as a static member of an outer class. As it is a static member, we can
access it without initializing the outer class with the help of a static method. So, we can say that
technically Static Inner classes are not a Java inner class.
Similar to static members, a static nested class cannot access the instance variables and methods
of the outer class.

package com.mypack.innerclass;
public class OuterClassDemo
{
static class NestedDemo
{
public void myMethod()
{
System.out.println("This is a static nested class");
}
public static void main(String args[])
{
//Accessing the static nested class without initializing the object //of Outer class
OuterClassDemo.NestedDemo nested = new
OuterClassDemo.NestedDemo();
nested.myMethod();
}
}
}

Output:

This is a static nested class

4. Anonymous Inner class

Anonymous inner class is an inner class that is declared without a name. It helps you to make a
more concise code. Generally, they are used when there is a need to override the method of a
class or an interface. We can also use them if we need to use a local class only once. They are
similar to local inner classes with the exception that they do not have a name.

package com.mypack.innerclass;
interface AnonymousAnimal
{
void type();
}
public class AnonymousInnerClass
{
public static void main(String args[])
{
AnonymousAnimal animal = new AnonymousAnimal(){
public void type()
{
System.out.println("Anonymous Anteater");
System.out.println("Anonymous Unicorn");
System.out.println("Anonymous Capybara");
System.out.println("Anonymous Beaver");
}
};
animal.type();
}
}
Output:
Anonymous Anteater
Anonymous Unicorn
Anonymous Capybara
Anonymous Beaver

Repaint method

The paint () method is called automatically by the environment (usually a web browser) that
contains the applet whenever the applet window needs to be redrawn. This happens when the
component is first displayed, but it can happen again if the user minimizes the window that
displays the component and then restores it or if the user moves another window over it and then
move that window out of the way. In addition to these implicit calls to the paint() method by the
environment, one can also call the paint () method explicitly whenever the applet window needs
to be redrawn, using the repaint () method.

The repaint () method causes the AWT runtime system to execute the update () method of the
Component class which clears the window with the background color of the applet and then calls
the paint () method. For example: Suppose you want to display the current x and y coordinates of
the location where the mouse button is clicked in the applet window. As the applet needs to
update information displayed in its window (i.e. redraw the window), each time the mouse is
being clicked so this is possible with the use of repaint () method. To sum up, the repaint()
method is invoked to refresh the viewing area i.e. you call it when you have new things to
display.

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="RepaintJavaExample.class" width="350" height="150"> </applet>*/
public class RepaintJavaExample extends Applet implements MouseListener
{
        private int mouseX, mouseY;
        private boolean mouseclicked = false;
        public void init()
        {
          setBackground(Color.CYAN);
          addMouseListener(this);
        }
        public void mouseClicked(MouseEvent e)
        {
          mouseX = e.getX();
          mouseY=e.getY();
          mouseclicked = true;
          repaint();
        }
        public void mouseEntered(MouseEvent e){};
        public void mousePressed(MouseEvent e){};
        public void mouseReleased(MouseEvent e){};
        public void mouseExited(MouseEvent e){};
        public void paint( Graphics g )
        {
           String str;
           g.setColor(Color.RED);
           if (mouseclicked)
           {
             str = "X="+ mouseX + "," + "Y="+ mouseY ;
             g.drawString(str,mouseX,mouseY);
             mouseclicked = false;    
           }
        }
}

Status Window

An applet can output a message to the status window of the browser or applet viewer on which it
is running. For this, it makes a call to showStatus( ) with the string that we want to be displayed.
The status window is a place where the user can give feedback about what is occurring in the
applet, suggest options, or report some types of errors. The status window also makes an
excellent debugging aid, because it gives an easy way to output information about the applet.
The applet below shows the use of showStatus( ):

 import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=50> </applet>
*/
public class StatusWindow extends Applet
{
           public void init()
      {
           setBackground(Color.pink);
      }
           public void paint (Graphics g)
       {
          g.drawString("You are in main applet window.", 10, 20);
          showStatus("This is the status window.");
       }
}

What is the getCodeBase () method?


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.

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. The getCodeBase() method returns the complete URL of
the . class file that contains the applet.

In most of the applets, it is required to load text and images explicitly. Java enables loading data
from two directories. The first one is the directory which contains the HTML file that started the
applet (known as the document base). The other one is the directory from which the class file of
the applet is loaded (known as the code base). These directories can be obtained as URL objects
by using getDocumentBase ()and getCodeBase ()methods respectively. You can concatenate
these URL objects with the string representing the name of the file that is to be loaded.

Here is the java code for the program GetDocumentBase and getCodeBase Example :.*/

/*
    <applet code="GetDocumentBaseExample" width=350 height=250>
    </applet>
    */
 
   import java.applet.Applet;
    import java.awt.Graphics;
    import java.net.URL;
    import java.awt.*;
    import java.awt.event.*;
     
    public class GetDocumentBaseExample extends Applet{
     
            public void paint(Graphics g){
            String message;
          
        //getCodeBase() method gets the base URL of the directory in which contains this applet.
         URL appletCodeDir=getCodeBase();
          message = "Code Base : "+appletCodeDir.toString();
          g.drawString(message,10,90);
         
         // getDocumentBase() Returns an absolute URL of the Document
          URL appletDocDir = getDocumentBase();        
          message="Document Base : "+appletDocDir.toString();
          g.drawString(message,10,120);
          g.drawString("https://ecomputernotes.com", 200, 250);
                  
                   
            }
    }

Java allows the applet to transfer the control to another URL by using the showDocument ()
Method defined in the AppletContext interface. For this, first of all, it is needed to obtain the
Context of the currently executing applet by calling the getAppletContext () method defined by
the Applet. Once the context of the applet is obtained with in an applet, another document can be
brought into view by calling showDocument () method.

There are two showDocument () methods which are as follows:


showDocument(URL url)
showDocument(URL url,string lac)
where,
url is the URL from where the document is to be brought into view.
loc is the location within the browser window where the specified document is to be displayed.

Example An applet code to demonstrate the use of AppletContext and showDocument ().

import java.applet.Applet;
import java.applet.AppletContext;
import java.net.*;
/*
<applet code=”LoadHTMLFileSample” width=”700″ height=”500″></applet>
*/
public class LoadHTMLFileSample extends Applet
{
    public void start()
    {
          AppletContext context= getAppletContext();
          //get AppletContext
          URL codeBase = getCodeBase(); //get Applet code base
          try{
                 URL url = new URL(codeBase + “Test.html”);
                 context.showDocument(url,”_blank”);
                 repaint();
               }catch(MalformedURLException mfe) {
                         mfe.printStackTrace();
                         }
     }
}
AudioClip interface

What is audio clip interface and what are all the methods in it?
The AudioClip interface defines these methods: play( ) (play a clip from the beginning),
stop( ) (stop playing the clip), and loop( ) (play the loop continuously). After you have loaded
an audio clip using getAudioClip( ), you can use these methods to play it.

AppletStub Interface. When an applet is first created, an applet stub is attached to it using the
applet's setStub method. This stub serves as the interface between the applet and the browser
environment or applet viewer environment in which the application is running.

If a data object is shared by multiple processes, some threads only need to read the data, while
others need to modify the data. This is known as the reader writer problem. If a write thread is in
the process of writing, it is forbidden to read any thread.

Readers Writers Problem

The readers-writers problem is a classical problem of process synchronization, it relates to a data


set such as a file that is shared between more than one process at a time. Among these various
processes, some are Readers - which can only read the data set; they do not perform any updates,
some are Writers - can both read and write in the data sets.

The readers-writers problem is used for managing synchronization among various reader and
writer process so that there are no problems with the data sets, i.e. no inconsistency is generated.

Let's understand with an example - If two or more than two readers want to access the file at the
same point in time there will be no problem. However, in other situations like when two writers
or one reader and one writer wants to access the file at the same point of time, there may occur
some problems, hence the task is to design the code in such a manner that if one reader is reading
then no writer is allowed to update at the same point of time, similarly, if one writer is writing no
reader is allowed to read the file at that point of time and if one writer is updating a file other
writers should not be allowed to update the file at the same point of time. However, multiple
readers can access the object at the same time.

In computing, the producer-consumer problem (also known as the bounded-buffer problem) is


a classic example of a multi-process synchronization problem. The problem describes two
processes, the producer and the consumer, which share a common, fixed-size buffer used as a
queue. 

 The producer’s job is to generate data, put it into the buffer, and start again.
 At the same time, the consumer is consuming the data (i.e. removing it from the buffer),
one piece at a time.

Problem 
To make sure that the producer won’t try to add data into the buffer if it’s full and that the
consumer won’t try to remove data from an empty buffer.

Solution 
The producer is to either go to sleep or discard data if the buffer is full. The next time the
consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer
again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next
time the producer puts data into the buffer, it wakes up the sleeping consumer. 
An inadequate solution could result in a deadlock where both processes are waiting to be
awakened. 

You might also like