API java : EventHandler


java.beans
Class EventHandler

java.lang.Object
  extended by java.beans.EventHandler
All Implemented Interfaces:
InvocationHandler

public class EventHandler
extends Object
implements InvocationHandler

The EventHandler class provides support for dynamically generating event listeners whose methods execute a simple statement involving an incoming event object and a target object.

The EventHandler class is intended to be used by interactive tools, such as application builders, that allow developers to make connections between beans. Typically connections are made from a user interface bean (the event source) to an application logic bean (the target). The most effective connections of this kind isolate the application logic from the user interface. For example, the EventHandler for a connection from a JCheckBox to a method that accepts a boolean value can deal with extracting the state of the check box and passing it directly to the method so that the method is isolated from the user interface layer.

Inner classes are another, more general way to handle events from user interfaces. The EventHandler class handles only a subset of what is possible using inner classes. However, EventHandler works better with the long-term persistence scheme than inner classes. Also, using EventHandler in large applications in which the same interface is implemented many times can reduce the disk and memory footprint of the application.

The reason that listeners created with EventHandler have such a small footprint is that the Proxy class, on which the EventHandler relies, shares implementations of identical interfaces. For example, if you use the EventHandler create methods to make all the ActionListeners in an application, all the action listeners will be instances of a single class (one created by the Proxy class). In general, listeners based on the Proxy class require one listener class to be created per listener type (interface), whereas the inner class approach requires one class to be created per listener (object that implements the interface).

You don't generally deal directly with EventHandler instances. Instead, you use one of the EventHandler create methods to create an object that implements a given listener interface. This listener object uses an EventHandler object behind the scenes to encapsulate information about the event, the object to be sent a message when the event occurs, the message (method) to be sent, and any argument to the method. The following section gives examples of how to create listener objects using the create methods.

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. In the following example we create an ActionListener that invokes the toFront method on an instance of javax.swing.JFrame.
  1. myButton.addActionListener(
  2. (ActionListener)EventHandler.create(ActionListener.class, frame, "toFront"));
When myButton is pressed, the statement frame.toFront() will be executed. One could get the same effect, with some additional compile-time type safety, by defining a new implementation of the ActionListener interface and adding an instance of it to the button:
  1. //Equivalent code using an inner class instead of EventHandler.
  2. myButton.addActionListener(new ActionListener() {
  3. public void actionPerformed(ActionEvent e) {
  4. frame.toFront();
  5. }
  6. });
The next simplest use of EventHandler is to extract a property value from the first argument of the method in the listener interface (typically an event object) and use it to set the value of a property in the target object. In the following example we create an ActionListener that sets the nextFocusableComponent property of the target object to the value of the "source" property of the event.
  1. EventHandler.create(ActionListener.class, target, "nextFocusableComponent", "source")
This would correspond to the following inner class implementation:
  1. //Equivalent code using an inner class instead of EventHandler.
  2. public void actionPerformed(ActionEvent e) {
  3. button.setNextFocusableComponent((Component)e.getSource());
  4. }
  5. }
Probably the most common use of EventHandler is to extract a property value from the source of the event object and set this value as the value of a property of the target object. In the following example we create an ActionListener that sets the "label" property of the target object to the value of the "text" property of the source (the value of the "source" property) of the event.
  1. EventHandler.create(ActionListener.class, button, "label", "source.text")
This would correspond to the following inner class implementation:
  1. //Equivalent code using an inner class instead of EventHandler.
  2. public void actionPerformed(ActionEvent e) {
  3. button.setLabel(((JTextField)e.getSource()).getText());
  4. }
  5. }
The event property may be be "qualified" with an arbitrary number of property prefixes delimited with the "." character. The "qualifying" names that appear before the "." characters are taken as the names of properties that should be applied, left-most first, to the event object.

For example, the following action listener

  1. EventHandler.create(ActionListener.class, target, "a", "b.c.d")
might be written as the following inner class (assuming all the properties had canonical getter methods and returned the appropriate types):
  1. //Equivalent code using an inner class instead of EventHandler.
  2. public void actionPerformed(ActionEvent e) {
  3. target.setA(e.getB().getC().isD());
  4. }
  5. }

Since:
1.4
See Also:
Proxy, EventObject

Constructor Summary
EventHandler(Object target, String action, String eventPropertyName, String listenerMethodName)
          Creates a new EventHandler object; you generally use one of the create methods instead of invoking this constructor directly.
 
Method Summary
static
<T> T
create(Class<T> listenerInterface, Object target, String action)
          Creates an implementation of listenerInterface in which all of the methods in the listener interface apply the handler's action to the target.
static
<T> T
create(Class<T> listenerInterface, Object target, String action, String eventPropertyName)
          Creates an implementation of listenerInterface in which all of the methods pass the value of the event expression, eventPropertyName, to the final method in the statement, action, which is applied to the target.
static
<T> T
create(Class<T> listenerInterface, Object target, String action, String eventPropertyName, String listenerMethodName)
          Creates an implementation of listenerInterface in which the method named listenerMethodName passes the value of the event expression, eventPropertyName, to the final method in the statement, action, which is applied to the target.
 String getAction()
          Returns the name of the target's writable property that this event handler will set, or the name of the method that this event handler will invoke on the target.
 String getEventPropertyName()
          Returns the property of the event that should be used in the action applied to the target.
 String getListenerMethodName()
          Returns the name of the method that will trigger the action.
 Object getTarget()
          Returns the object to which this event handler will send a message.
 Object invoke(Object proxy, Method method, Object[] arguments)
          Extract the appropriate property value from the event and pass it to the action associated with this EventHandler.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

EventHandler

public EventHandler(Object target,
                    String action,
                    String eventPropertyName,
                    String listenerMethodName)
Creates a new EventHandler object; you generally use one of the create methods instead of invoking this constructor directly.

Parameters:
target - the object that will perform the action
action - the (possibly qualified) name of a writable property or method on the target
eventPropertyName - the (possibly qualified) name of a readable property of the incoming event
listenerMethodName - the name of the method in the listener interface that should trigger the action
See Also:
EventHandler, create(Class, Object, String, String, String), getTarget(), getAction(), getEventPropertyName(), getListenerMethodName()
Method Detail

getTarget

public Object getTarget()
Returns the object to which this event handler will send a message.

Returns:
the target of this event handler
See Also:
EventHandler(Object, String, String, String)

getAction

public String getAction()
Returns the name of the target's writable property that this event handler will set, or the name of the method that this event handler will invoke on the target.

Returns:
the action of this event handler
See Also:
EventHandler(Object, String, String, String)

getEventPropertyName

public String getEventPropertyName()
Returns the property of the event that should be used in the action applied to the target.

Returns:
the property of the event
See Also:
EventHandler(Object, String, String, String)

getListenerMethodName

public String getListenerMethodName()
Returns the name of the method that will trigger the action. A return value of null signifies that all methods in the listener interface trigger the action.

Returns:
the name of the method that will trigger the action
See Also:
EventHandler(Object, String, String, String)

invoke

public Object invoke(Object proxy,
                     Method method,
                     Object[] arguments)
Extract the appropriate property value from the event and pass it to the action associated with this EventHandler.

Specified by:
invoke in interface InvocationHandler
Parameters:
proxy - the proxy object
method - the method in the listener interface
arguments - an array of objects containing the values of the arguments passed in the method invocation on the proxy instance, or null if interface method takes no arguments. Arguments of primitive types are wrapped in instances of the appropriate primitive wrapper class, such as java.lang.Integer or java.lang.Boolean.
Returns:
the result of applying the action to the target
See Also:
EventHandler

create

public static <T> T create(Class<T> listenerInterface,
                           Object target,
                           String action)
Creates an implementation of listenerInterface in which all of the methods in the listener interface apply the handler's action to the target. This method is implemented by calling the other, more general, implementation of the create method with both the eventPropertyName and the listenerMethodName taking the value null.

To create an ActionListener that shows a JDialog with dialog.show(), one can write:

  1. EventHandler.create(ActionListener.class, dialog, "show")

Parameters:
listenerInterface - the listener interface to create a proxy for
target - the object that will perform the action
action - the name of a writable property or method on the target
Returns:
an object that implements listenerInterface
See Also:
create(Class, Object, String, String)

create

public static <T> T create(Class<T> listenerInterface,
                           Object target,
                           String action,
                           String eventPropertyName)
Creates an implementation of listenerInterface in which all of the methods pass the value of the event expression, eventPropertyName, to the final method in the statement, action, which is applied to the target. This method is implemented by calling the more general, implementation of the create method with the listenerMethodName taking the value null.

To create an ActionListener that sets the the text of a JLabel to the text value of the JTextField source of the incoming event, you can use the following code:

  1. EventHandler.create(ActionListener.class, label, "text", "source.text");
This is equivalent to the following code:
  1. //Equivalent code using an inner class instead of EventHandler.
  2. label.setText((JTextField(event.getSource())).getText())

Parameters:
listenerInterface - the listener interface to create a proxy for
target - the object that will perform the action
action - the name of a writable property or method on the target
eventPropertyName - the (possibly qualified) name of a readable property of the incoming event
Returns:
an object that implements listenerInterface
See Also:
create(Class, Object, String, String, String)

create

public static <T> T create(Class<T> listenerInterface,
                           Object target,
                           String action,
                           String eventPropertyName,
                           String listenerMethodName)
Creates an implementation of listenerInterface in which the method named listenerMethodName passes the value of the event expression, eventPropertyName, to the final method in the statement, action, which is applied to the target. All of the other listener methods do nothing.

If the eventPropertyName is null the implementation calls a method with the name specified in action that takes an EventObject or a no-argument method with the same name if a method accepting an EventObject is not defined.

If the listenerMethodName is null all methods in the interface trigger the action to be executed on the target.

For example, to create a MouseListener that sets the target object's origin property to the incoming MouseEvent's location (that's the value of mouseEvent.getPoint()) each time a mouse button is pressed, one would write:

  1. EventHandler.create(MouseListener.class, "mousePressed", target, "origin", "point");
This is comparable to writing a MouseListener in which all of the methods except mousePressed are no-ops:
  1. //Equivalent code using an inner class instead of EventHandler.
  2. new MouseAdapter() {
  3. public void mousePressed(MouseEvent e) {
  4. target.setOrigin(e.getPoint());
  5. }
  6. }

Parameters:
listenerInterface - the listener interface to create a proxy for
target - the object that will perform the action
action - the name of a writable property or method on the target
eventPropertyName - the (possibly qualified) name of a readable property of the incoming event
listenerMethodName - the name of the method in the listener interface that should trigger the action
Returns:
an object that implements listenerInterface
See Also:
EventHandler

Ces informations proviennent du site de http://java.sun.com

Remarques

Contenu

Le contenu de cette page provient du site de Sun, et est généré depuis un cache sur l'infobrol après certains traitements automatisés. La présentation peut donc différer du document original, mais le contenu aussi. Vous pouvez utiliser ce bouton pour afficher la page originale du site de Sun :

Quels sont les motivations de cette démarche?

Maintenir les pages en cache sur différents sites peut offrir plus de disponibilité.

Chaque page est indexée dans la base de donnée, ce qui permet de retrouver facilement les informations, au moyen des sommaires, du moteur de recherche interne, etc.

Des facilités sont mises en place pour que les membres de l'infobrol puissent effectuer des traductions en français des différents documents. Ceci devrait permettre aux débutants en programmation Java de consulter les API en français s'ils maîtrisent moins bien la langue de Shakespeare. Dans le cas où une traduction a été soumise, elle est disponible au moyen d'un lien en bas de page. Si la traduction a été validée, la page s'affiche par défaut en français, et un lien en bas de page permet d'atteindre la version en anglais.

Le code sur l'infobrol est automatiquement coloré selon la syntaxe, et les différents mots clés sont transformés en liens pour accéder rapidement aux informations.

Vous avez la possibilité de partager vos expériences en proposant vos propres extraits de code en utilisant le bouton "ajouter un commentaire" en bas de page. Si vous visitez simplement l'infobrol, vous avez déjà accès à cette fonction, mais si vous étes membre du brol, vous pouvez en plus utiliser des boutons supplémentaires de mise en forme, dont la coloration automatique de vos extraits de codes.

Réseaux sociaux

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher les interactions avec les réseaux sociaux sur ces pages.

 

Nuage de mots clés

7 mots clés dont 0 définis manuellement (plus d'information...).

Avertissement

Cette page ne possède pas encore de mots clés manuels, ceci est donc un exemple automatique (les niveaux de pertinence sont fictifs, mais les liens sont valables). Pour tester le nuage avec une page qui contient des mots définis manuellement, vous pouvez cliquer ici.

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher le nuage de mots clés.

 

Astuce pour imprimer les couleurs des cellules de tableaux : http://www.gaudry.be/ast-rf-450.html
Aucun commentaire pour cette page

© Ce document issu de l′infobrol est enregistré sous le certificat Cyber PrInterDeposit Digital Numbertection. Enregistrement IDDN n° 5329-783
Document créé le 27/07/06 15:18, dernière modification le Vendredi 17 Juin 2011, 12:12
Source du document imprimé : http://www.gaudry.be/java-api-rf-java/beans/EventHandler.html Document affiché 1 fois ce mois de Juin.
St.Gaudry©07.01.02
Outils (masquer)
||
Recherche (afficher)
Recherche :

Utilisateur (masquer)
Apparence (afficher)
Stats (afficher)
15832 documents
452 astuces.
549 niouzes.
3099 definitions.
447 membres.
8115 messages.

Document genere en :
2,05 secondes

Mises à jour :
Mises à jour du site
Citation (masquer)
Aimer, c'est trouver, grâce à un autre, sa vérité et aider cet autre à trouver la sienne. C'est créer une complicité passionnée.

Jacques de Bourbon Busset
 
l'infobrol
Nous sommes le Vendredi 01 Juin 2012, 15:04, toutes les heures sont au format GMT+1.00 Heure, heure d'été (+1)