top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Event Handling in Java

0 votes
241 views

Event Handling

Event handling is fundamental to java programming because it is integral to the creation of applets and other types of GUI-based programs. Events are supported by a number of packages, including java.util, java.awt, and java.awt.event.

Most events to which your program will respond are generated when the user interacts with a GUI-based program. These are the types of events, they are passed to your program in a variety of ways, with the specific method dependent upon the actual event. There are several types of events, including those generated by the mouse, the keyboard, and various GUI controls, such as a push button, scroll bar, or check box.

Two Event Handling Mechanisms

Before beginning our discussion of event handling, an important point must be made: The way in which events are handled changed significantly between the original version of Java(1.0) and modern version of java, beginning with version 1.1. The 1.0 method of event handling is still supported, but it is not recommended for new programs. Also, many of the methods that supported the old 1.0 event model have been deprecated. The modern approach is the way that events should be handled by all new programs and thus is the method employed by programs.

The delegation Event Model

The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once an event is received, the listener processes the event and then returns. 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. A user interface elements is able to “delegate” the processing of an event to a separate piece of code.

Note: Java also allows you to process events without using the delegation event mode. However, the delegation event model is the preferred design for the reason just cited.

Events

In 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. Many other user operations could also be cited as examples.

Events 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. You are free to define events that are appropriate for your application.

Event Sources

A 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)

Here, Type is the name of the event, and el is a reference to the event listener. For example, the method that registers a keyboard event listener is called addKeyListener(). The method that registers a mouse motion listener is called addMouseMotionListener(). When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent only to listeners that register to receive them:

Some sources may allow only one listener to register. The general form of such a method is this:

Public void addTypeListener(TypeListener el)

throws java.util.TooManyListnersException

Here, Type is the name of the event, and el is a reference to the event listener. When such an event occurs, the registered listener is notified. This is known as unicasting the event. A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general form of such a method is this:

Public void removeTypeListener(TypeListener el)

Here, Type is the name of the event, and el is a reference to the event listener. For example, to remove a keyboard listener, you would call removeKeyListener(). The methods that add or remove listeners are provided by the source that generates events. For example, the component class provides methods to add and remove keyboard and mouse event listeners.

Event Listeners

A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.

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

posted Jan 18, 2018 by Frank Lee

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Causes of Exceptions

An exception is an abnormal condition that arises out of an extraordinary situation disrupting the flow of program’s instructions. Exceptions report error conditions in a program.

                                    

In programs, exceptions can occur due to any of the following reasons:

  • Programming errors: These exceptions arise due to errors present in APIs, such as NullPointerException. The program using these APIs cannot do anything about these errors.
  • Client code errors: The client code attempts operations, such as reading content from a file without opening it. This will raise an exception. The exception will provide information about the cause of the error and is handled by the client code.
  • Errors beyond the control of a program: There are certain exceptions that are not expected to be caught by the client code such as memory error or network connection failure error. These are errors which have been raised by the run-time environment.

                                                                                      

Classification of Exceptions

When an error occurs in a method during runtime, an object is created containing information about the error, its type and the state of the program. This object is referred to as exception object. Exception objects are instances of classes that are derived from the base class Throwable.

In Java there are two types of exceptions. They are:

  • Checked Exceptions: These types of exceptions are derived from the Exception class. The program either handles the checked exception or moves the exception further up the stack. It is checked during compilation.
  • Unchecked Exception: These exceptions are derived from the RuntimeException class, Which in turn is derived from the Exception class. The program need not handle unchecked exception. It is generated during the execution of the program.

 

Types of Checked Exceptions

All checked exceptions are derived from the Exception class. Some of the common checked exceptions are:-

InstantiationException: This exception occurs if an attempt is made to create an instance of the abstract class.

InterruptedException: This exception occurs if a thread is interrupted.

NoSuchMethodException: This exception occurs if the java virtual Machine is unable to resolve which method is to be called.

RuntimeException: This exception may be thrown during normal operation of java virtual machine if some erroneous condition occurs.

 

Types of Unchecked Exceptions

All Unchecked exceptions are directly or directly or indirectly derived from the RuntimeException class. Some of the common Unchecked exceptions are described:

ArithmeticException: Derived from RuntimeException and indicates an Arithmetic error condition.

ArrayIndexOutOfBoundsException: Derived from RuntimeException. Method receives an illegal arugument.

NegativeArraySizeException: Derived from RuntimeException. Array size is less than zero.

NullPointerException: Derived from RuntimeException. Attempt to access a null object member.

NumberFormatException: Derived from IllegalArgumentException. Unable to convert the string to a number.

StringIndexOutOfBoundsException: Derived from IndexOutOfBoundsException. Index is negative or greater than the size of the string.

READ MORE

In the previous part of this series I discussed how HTML DOM can be manipulated using jQuery. Now let's proceed with one of the most common task you do in JavaScript - handling events. jQuery streamlines the JavaScript event handling mechanism by providing you a uniform and easy way to wire events with their handlers without bothering about the cross browser issues. The following table lists some frequently used jQuery events :

EventDescription
clickOccurs when you click on an element
dblclickOccurs when you double click on an element
hoverAllows you to trap mouse entry and exit from an element
mousedownOccurs when a mouse button is pressed but not yet released
mouseupOccurs when a pressed mouse button is released
keydownOccurs when a keyboard key is pressed but is yet to be released
keyupOccurs when a keyboard key is released
keypressOccurs when any of the input key is pressed. Normally used when you are only interested in data entered and not in state of Shift or Ctrl keys.
blurOccurs when focus leaves an element
focusOccurs when an element receives focus
changeOccurs when value of <input>, <textarea> and <select> changes.
selectOccurs when text is selected from <input> or <textarea>
submitOccurs when a form is being submitted. Valid only on <form> element.
resizeOccurs when browser windows is resized
readyOccurs when DOM tree is completely loaded

One nice feature about jQuery event handling is the event object that gets passed to the handlers in a standard way. The event object passed to the event handlers contain several pieces of information about the event such as :

Event object property / methodDescription
targetThe DOM element that triggered the event
dataUser specific data passed to the event handler. This is optional.
pageXX coordinate of mouse within the document
pageYY coordinate of mouse within the document
preventDefault()Allows you to cancel the default action on an event (say form submission when clicked on Submit buttons)
whichIndicates the key code of the keyboard key that was pressed
typeType of the event such as click or keydown
altKeyReturns true/false depending on whether ALT key is pressed on not
shiftKeyReturns true/false depending on whether SHIFT key is pressed on not
ctrlKeyReturns true/false depending on whether CTRL key is pressed on not

To understand how event handling as described above works let's develop an example. In this example we will create a custom context menu (shortcut menu or right click menu) that displays some options specific to our website instead of the normal context menu of the browser. See below for an example :

image

Begin by adding a new web form and add script reference to jQuery library as before. Then add a <DIV> somewhere in the HTML body as shown below :

<div id="menuContainer"></div>

Our custom context menu will be a DIV with ID menuContainer. We won't store menu options statically. Rather we will put them in an XML file and then retrieve them from jQuery code. The XML file that contains the menu options has the following structure :

<menu>
    <menuitem id="item1" text="Home Page" navigateUrl="url1.aspx"></menuitem>
    <menuitem id="item2" text="--"></menuitem>
    <menuitem id="item3" text="Login"></menuitem>
    <menuitem id="item4" text="Administer Users" navigateUrl="url3.aspx"></menuitem>
    <menuitem id="item5" text="Check Email" navigateUrl="url4.aspx"></menuitem>
    <menuitem id="item6" text="--"></menuitem>
    <menuitem id="item7" text="View Orders" navigateUrl="url6.aspx"></menuitem>
</menu>

The root tag is <menu>. In this example we won't go into nested menus. Each menu item is represented by <menuitem> element. The three possible attributes of <menuitem> element are id, text and navigateUrl. The id attribute uniquely identifies a menu item and is used on client side to determine which menu option was clicked by the user. The text attribute indicates the menu item text and the navigateUrl attribute attribute indicates the target URL. If navigateUrl attribute is missing then the menu item becomes clickable one. If text attribute is -- then a menu separator (<HR>) is added.

Now switch to the HTML source view of the web form and define two CSS classes as shown below :

.Hover
{
    background-color:silver;
    cursor:hand;
}
.MenuPad
{
    background-color:whitesmoke;
    border:solid 1px gray;
    width:200px;
    position:absolute;
}

The Hover CSS class defines the appearance of a menu item under the mouse pointer. The MenuPad CSS class defines the overall appearance of the context menu. Notice that MenuPad class sets the position attribute to absolute because we want to display the context menu at the place where user right clicks.

Add a <script> block in the head section of the web form and set ready event handler as shown below :

$(document).ready(OnReady);

The OnReady function looks like this :

function OnReady() {
    $.get("Menu.xml", OnSuccess);
    $(document)[0].oncontextmenu = function() { return false; }
    $(document).mousedown(function(event) {
        if (event.which == 3) {
            $("#menuContainer").css("left", event.pageX)
                               .css("top", event.pageY)
                               .show();
        }
    })
    ,
    $(document).keydown(function(event) {
        if (event.which == 27) {
            $("#menuContainer").hide();
        }
    })
    
}

The OnReady event handler essentially does four things. Firstly, it retrieves the menu definition file Menu.xml residing on the server. It does so using get() method you learnt in the previous part. The OnSuccess() function will be called upon successfully retrieving Menu.xml. OnSuccess() function is discussed later. Secondly, it suppresses the browser's default context menu from popping up. It is done by handling oncontextmenu event and then returning false from the event handler so that the event is cancelled. Then it handles mousedown and keydown events of document object.

Notice how the event object is passed to the event handler. The mousedown event handler checks the which property of the event object to determine which mouse button was clicked. The value of 3 indicates right click. It then sets the left and top properties using css() method. The event.pageX and event.pageY will give you the mouse pointer coordinates within the document. The show() method makes the menuContainer visible. You could have also set visible attribute to visible but using show() is easier.

The displayed context menu can be discarded by pressing Escape key. The keydown event handler again checks which property and if it is 27 (key code for Esc key) then it hides the menuContainer using hide() method.

The OnSuccess function receives XML menu definition and is shown below :

function OnSuccess(menuData) {
    $(menuData).find("menuitem").each(ProcessMenuItem);
    $("#menuContainer").addClass("MenuPad")
                       .hide();
    $("#menuContainer div").hover(OnMouseOver, OnMouseOut)
                           .css("padding", "5px");
}

For each <menuitem> element it calls ProcessMenuItem function. The ProcessMenuItem function add individual menu items to the menuContainer. Initially when the page loads the menuContainer is invisible. So after adding all the menu items we hide the menuContainer. We also handle hover() event for each menu item <DIV> element. The hover event takes two functions one that is called when mouse enters the element and another that is called when mouse leaves the element. The OnMouseOver and OnMouseOut functions are shown below :

function OnMouseOver(event) {
    $(this).addClass("Hover");
}

function OnMouseOut(event) {
    $(this).removeClass("Hover");
}

The OnMouseOver function adds Hover CSS class to the current menu item using addClass() method. Similarly, OnMouseOut function removes the Hover CSS class using removeClass() method.

function ProcessMenuItem(index) {
    var item = $(this);
    var text = item.attr("text");
    var url = item.attr("navigateUrl");

    var menuItemHtml = "";
    if (text == "--") {
        menuItemHtml = "<hr />";
    }
    else if(url==null) {
        menuItemHtml = "<div>" + text + "</div>";
    }
    else {
        menuItemHtml = "<div>" +
                       "<a href='" + url + "'>" + text + "</a>" +
                       "</div>";
    }
    $("#menuContainer").append(menuItemHtml);
    if (url == null) {
        $("#menuContainer div:last-child")
            .click({ menuItemId: text }, OnMenuItemClick); 
    }

}

The ProcessMenuItem function is an important one because menu items are added along with their handlers in this function. The ProcessMenuItem function first retrieves the text and navigateUrl attribute values. If text property is -- we wish to add a menu separator in the form of <HR> element. If the URL is specified we wish to display a hyperlink otherwise we simple display menu item text. The new menu item is appended to the menuContainer using append() method (you learnt about append() method in the previous part). Notice the last line carefully. Here, we handle click event of the last menu item. This way click event handler will be attached only to the recently added menu item. Note the first parameter of click event i.e. the one in { and }. This is how you can pass custom data to the event handler (OnMenuItemClick in our case). The first part i.e. menuItemId will appear as a property of event.data object and the later is its value. You can pass multiple pieces of information by separating them with a comma (,) e.g. { piece1:val1,piece2:val2 }.

function OnMenuItemClick(event) {
    alert("You clicked : " + event.data.menuItemId);
    $("#menuContainer").hide();
}

The OnMouseClick function is called when user clicks on a menu item that doesn't have navigateUrl attribute. Notice how we access the custom event data (event.data.menuItemId  ). You can use this menuItemId to have a if...else or switch...case statements and perform different actions depending on the menu item clicked. Once the menu item action is performed we hide the menuContainer.

In the next part I will discuss some of the effects that can jazz up your HTML elements. Stay tuned!

READ MORE
...