General Information about Writing Event Listeners

● Design Considerations
● Getting Event Information: Event Objects
● Concepts: Low-Level Events and Semantic Events
● Event Adapters
● Inner Classes and Anonymous Inner Classes
● The EventHandler Class

Design Considerations

The most important rule to keep in mind about event listeners is that they should execute very quickly. Because all drawing and event-listening methods are executed in the same thread, a slow event-listener method can make the program seem unresponsive and slow to repaint itself. If you need to perform some lengthy operation as the result of an event, do it by starting up another thread to perform the operation.

You have many choices on how to implement an event listener. We can not recommend a specific approach because one solution would not suit all situations.
When designing your program, you might want to implement your event listeners in a class that is not public, but somewhere more hidden. A private implementation is a more secure implementation.
If you have a very specific kind of simple event listener, you might be able to avoid creating a class at all by using the EventHandler class.

Event Objects

Every event-listener method has a single argument an object that inherits from the EventObject class. Although the argument always descends from EventObject.
The EventObject class defines one very useful method:

Object getSource()
Returns the object that fired the event.

The getSource method returns an Object. Event classes sometimes define methods similar to getSource, but that have more restricted return types. The difference is that getComponent always returns a Component. Each how-to page for event listeners mentions whether you should use getSource or another method to get the event source.
Often, an event class defines methods that return information about the event.

Low-Level Events and Semantic Events

Events can be divided into two groups: low-level events and semantic events. Low-level events represent window-system occurrences or low-level input. Everything else is a semantic event.
Examples of low-level events include mouse and key events both of which result directly from user input. Examples of semantic events include action and item events. A semantic event might be triggered by user input; for example, a button customarily fires an action event when the user clicks it, and a text field fires an action event when the user presses Enter.
Whenever possible, you should listen for semantic events rather than low-level events. That way, you can make your code as robust and portable as possible. For example, listening for action events on buttons, rather than mouse events, means that the button will react appropriately when the user tries to activate the button using a keyboard alternative or a look-and-feel-specific gesture.

Event Adapters

Some listener interfaces contain more than one method. For example, the MouseListener interface contains five methods: mousePressed, mouseReleased, mouseEntered, mouseExited, and mouseClicked. Even if you care only about mouse clicks, if your class directly implements MouseListener, then you must implement all five MouseListener methods. Methods for those events you do not care about can have empty bodies. Here is an example:

//An example that implements a listener interface directly.

public class MyClass implements MouseListener {
    ...
        someObject.addMouseListener(this);
    ...
    /* Empty method definition. */
    public void mousePressed(MouseEvent e) {
    }

    /* Empty method definition. */
    public void mouseReleased(MouseEvent e) {
    }

    /* Empty method definition. */
    public void mouseEntered(MouseEvent e) {
    }

    /* Empty method definition. */
    public void mouseExited(MouseEvent e) {
    }

    public void mouseClicked(MouseEvent e) {
        ...//Event listener implementation goes here...
    }
}




The resulting collection of empty method bodies can make code harder to read and maintain. To help you avoid implementing empty method bodies, the API generally includes an adapter class for each listener interface with more than one method.
To use an adapter, you create a subclass of it and override only the methods of interest, rather than directly implementing all methods of the listener interface.


/*
 * An example of extending an adapter class instead of
 * directly implementing a listener interface.
 */
public class MyClass extends MouseAdapter {
    ... 
        someObject.addMouseListener(this);
    ... 
    public void mouseClicked(MouseEvent e) {
        ...//Event listener implementation goes here...
    }
}

Inner Classes and Anonymous Inner Classes

What if you want to use an adapter class, but do not want your public class to inherit from an adapter class? For example, suppose you write an applet, and you want your Applet subclass to contain some code to handle mouse events. Since the Java language does not permit multiple inheritance, your class cannot extend both the Applet and MouseAdapter classes. A solution is to define an inner class a class inside of your Applet subclass that extends the MouseAdapter class. Inner classes can also be useful for event listeners that implement one or more interfaces directly.


//An example of using an inner class.
public class MyClass extends Applet {
    ...
        someObject.addMouseListener(new MyAdapter());
    ...
    class MyAdapter extends MouseAdapter {
        public void mouseClicked(MouseEvent e) {
            ...//Event listener implementation goes here...
        }
    }
}

You can create an inner class without specifying a name this is known as an anonymous inner class. While it might look strange at first glance, anonymous inner classes can make your code easier to read because the class is defined where it is referenced.

Here is an example of using an anonymous inner class:

//An example of using an anonymous inner class.
public class MyClass extends Applet {
    ...
        someObject.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                ...//Event listener implementation goes here...
            }
        });
    ...
    }
}

Inner classes work even if your event listener needs access to private instance variables from the enclosing class. As long as you do not declare an inner class to be static, an inner class can refer to instance variables and methods just as if its code is in the containing class. To make a local variable available to an inner class, just save a copy of the variable as a final local variable.
To refer to the enclosing instance, you can use EnclosingClass.this.

The EventHandler Class

An EventHandler class supports dynamic generation of simple, one-statement event listeners. Although EventHandler is only useful for a certain type of extremely simple event listeners, it is worth mentioning for two reasons.

• Making an event listener that persistence can see and yet does not clog up your own classes with event listener interfaces and methods. • Not adding to the number of classes defined in an application this can help performance.

An EventHandler must be carefully constructed. If you make a mistake, you would not be notified at compile time it will throw an obscure exception at runtime. For this reason, EventHandlers are best created by a GUI builder. EventHandlers should be carefully documented. Otherwise you run the risk of producing hard-to-read code.
Examples of Using EventHandler The simplest use of EventHandler is to install a listener that calls a method on the target object with no arguments. following example we create an ActionListener that invokes the toFront method on an instance of javax.swing.JFrame.

myButton.addActionListener( (ActionListener)EventHandler.create(ActionListener.class, frame, "toFront"));

References By: oracle « Privious Post » « Next Post » share on :        :  

Love to hear your Views / Guidance / Recommendations on this Post…

Explore the Technology World

Computer Programming Terminologies Computer Programming Terminology is a general word for the group of specialized words or meanings relating to Computer Programming, and also the study of such t ...Read MoreNew features in JDK 12 with IntelliJ IDEADeveloped by JetBrains (formerly known as IntelliJ) ,IntelliJ IDEA is a Java integrated development environment (IDE) for developing computer software. It is av ...Read MoreGoogle Pay API Implementation Demo for AndroidIn this youtube Channel by Android Developers ,Learn how to implement the Google Pay API for Android with just a few lines of code and how it works with your ex ...Read MoreUnit Testing in .NET Core and Azure Devops pipelineUnit testing is a software testing method by which individual units of source code, usage procedures,sets of one or more computer program modules together with ...Read MoreThe mind behind Linux & GIT : Linus TorvaldsLinus Torvalds transformed technology twice — first with the Linux kernel, which helps power the Internet, and again with Git, the source code management ...Read MoreTensorflow and deep learningWith Tensorflow ,deep machine learning transitions from an area of research into mainstream software engineering. ...Read MoreJava program to return all possible permutations from collection of distinct numbersexample of Java program to return all possible permutations from collection of distinct numbers ...Read MoreReal Time Analytics with Spring Application Development FrameworkSpring is the most popular application development framework for enterprise Java.Millions of developers use Spring to build simple, truly portable, fast and fle ...Read MorePath Setting in Java When an application is launched from command prompt Windows OS searches for the executable program in the current working directory. The prompt throws an error ...Read MoreFacebook | whatsapp|Github | Twitter | LinkedIn | Youtube| reddit About | Cookies-Policy | Disclaimer | Site Map | Contact

Call / Visit for New Batch

Services

Why Join Us

  • ➯ Free Demo Classes
  • ➯ No Registration Fee
  • ➯ Interview Questions
  • ➯ Study Materials
  • ➯ Softwares
  • ➯ Aptitude & Reasoning
  • ➯ Placement Assitance

Address

  • MyJava Training Institute ,
  • Plot No.243 , shop No 14 ,
  • Secnd Floor , Zone-II ,
  • M.P.Nagar , Bhopal,
  • Madhya Pradesh ( 462011 )
  • ☎  08871209400 , 7987028543
  • 🌐 www.myjava.in
FacebookGoogle +TwitterYouTube

MyJava - java Training Institute