t
t
t
t
t t   13) Création de fenêtres & d'Applets
tttt
t
carrea) Préface carreb) Avant-propos carre1) Introduction sur les &laqo; objets » carre2) Tout est &laqo; objet » carre3) Contrôle du flux du programme carre4) Initialization & Cleanup carre5) Cacher l'implémentation carre6) Réutiliser les classes carre7) Polymorphisme carre8) Interfaces & classes internes carre9) Stockage des objets carre10) Error Handling with Exceptions carre11) Le système d’E/S de Java carre12) Identification dynamique de type 13) Création de fenêtres & d'Applets carre14) Les &laqo; Threads » multiples carre15) Informatique distribuée carreA) Passage et retour d'objets carreB) L'Interface Java Natif (JNI) carreC) Conseils pour une programation stylée en Java carreD) Resources
Texte original t Traducteur : P. Boite
t
t
///
Ce chapitre contient 14 pages
1 2 3 4 5 6 7 8 9 10 11 12 13 14
\\\
t t t
t t t
t
t t t
Struts separate components by a fixed amount, but glue is the opposite: it separates components by as much as possible. Thus it’s more of a “spring” than “glue” (and the design on which this was based was called “springs and struts” so the choice of the term is a bit mysterious). t Les struts séparent les composant d'une quantité fixe, mais glue fait le contraire : il sépare les composant d'autant que possible. C'est donc plus un spring (ressort) qu'une glue (et dans la conception sur laquelle ceci était basé, cela s'appelait springs et struts, ce qui rend un peu mystérieux le choix de ce terme).
t t t
//: c13:Box3.java // Using Glue. // <applet code=Box3 // width=450 height=300> </applet> import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class Box3 extends JApplet { public void init() { Box bv = Box.createVerticalBox(); bv.add(new JLabel("Hello")); bv.add(Box.createVerticalGlue()); bv.add(new JLabel("Applet")); bv.add(Box.createVerticalGlue()); bv.add(new JLabel("World")); Box bh = Box.createHorizontalBox(); bh.add(new JLabel("Hello")); bh.add(Box.createHorizontalGlue()); bh.add(new JLabel("Applet")); bh.add(Box.createHorizontalGlue()); bh.add(new JLabel("World")); bv.add(Box.createVerticalGlue()); bv.add(bh); bv.add(Box.createVerticalGlue()); getContentPane().add(bv); } public static void main(String[] args) { Console.run(new Box3(), 450, 300); } } ///:~ t
//: c13:Box3.java
// Utilisation de Glue.
// <applet code=Box3
// width=450 height=300> </applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;

public class Box3 extends JApplet {
  public void init() {
  Box bv = Box.createVerticalBox();
  bv.add(new JLabel("Hello"));
  bv.add(Box.createVerticalGlue());
  bv.add(new JLabel("Applet"));
  bv.add(Box.createVerticalGlue());
  bv.add(new JLabel("World"));
  Box bh = Box.createHorizontalBox();
  bh.add(new JLabel("Hello"));
  bh.add(Box.createHorizontalGlue());
  bh.add(new JLabel("Applet"));
  bh.add(Box.createHorizontalGlue());
  bh.add(new JLabel("World"));
  bv.add(Box.createVerticalGlue());
  bv.add(bh);
  bv.add(Box.createVerticalGlue());
  getContentPane().add(bv);
}
  public static void main(String[] args) {
  Console.run(new Box3(), 450, 300);
}
} ///:~
t t t
A strut works in one direction, but a rigid area fixes the spacing between components in both directions: t Un strut fonctionne dans une direction, mais une rigid area (surface rigide) fixe l'espace entre les composants dans chaque direction :
t t t
//: c13:Box4.java // Rigid Areas are like pairs of struts. // <applet code=Box4 // width=450 height=300> </applet> import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class Box4 extends JApplet { public void init() { Box bv = Box.createVerticalBox(); bv.add(new JButton("Top")); bv.add(Box.createRigidArea( new Dimension(120, 90))); bv.add(new JButton("Bottom")); Box bh = Box.createHorizontalBox(); bh.add(new JButton("Left")); bh.add(Box.createRigidArea( new Dimension(160, 80))); bh.add(new JButton("Right")); bv.add(bh); getContentPane().add(bv); } public static void main(String[] args) { Console.run(new Box4(), 450, 300); } } ///:~ t
//: c13:Box4.java
// Des Rigid Areas sont comme des paires de struts.
// <applet code=Box4
// width=450 height=300> </applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;

public class Box4 extends JApplet {
  public void init() {
  Box bv = Box.createVerticalBox();
  bv.add(new JButton("Top"));
  bv.add(Box.createRigidArea(
    new Dimension(120, 90)));
  bv.add(new JButton("Bottom"));
  Box bh = Box.createHorizontalBox();
  bh.add(new JButton("Left"));
  bh.add(Box.createRigidArea(
    new Dimension(160, 80)));
  bh.add(new JButton("Right"));
  bv.add(bh);
  getContentPane().add(bv);
}
  public static void main(String[] args) {
  Console.run(new Box4(), 450, 300);
}
} ///:~
t t t
You should be aware that rigid areas are a bit controversial. Since they use absolute values, some people feel that they cause more trouble than they are worth.
t Il faut savoir que les rigid areas sont un peu controversées. Comme elles utilisent des valeurs absolues, certaines personnes pensent qu'elles causent plus de problèmes qu'elles n'en résolvent.
t t t

The best approach?

t

La meilleure approche ?

t t t
Swing is powerful; it can get a lot done with a few lines of code. The examples shown in this book are reasonably simple, and for learning purposes it makes sense to write them by hand. You can actually accomplish quite a bit by combining simple layouts. At some point, however, it stops making sense to hand-code GUI forms—it becomes too complicated and is not a good use of your programming time. The Java and Swing designers oriented the language and libraries to support GUI building tools, which have been created for the express purpose of making your programming experience easier. As long as you understand what’s going on with layouts and how to deal with the events (described next), it’s not particularly important that you actually know the details of how to lay out components by hand—let the appropriate tool do that for you (Java is, after all, designed to increase programmer productivity).
t Swing est puissant; il peut faire beaucoup de choses en quelques lignes de code. Les exemples de ce livre sont raisonnablement simples, et dans un but d'apprentissage il est normal de les écrire à la main. On peut en fait réaliser pas mal de choses en combinant des layouts simples. A un moment donné, il devient cependant déraisonnable de coder à la main des formulaires de GUI. Cela devient trop compliqué et ce n'est pas une bonne manière d'utiliser son temps de programmation. Les concepteur de Java et de Swing ont orienté le langage et ses bibliothèques de manière à soutenir des outils de construction de GUI, qui ont été créés dans le but de rendre la tâche de programmation plus facile. A partir du moment où on comprend ce qui se passe dans les layouts et comment traiter les événements (décrits plus loin), il n'est pas particulièrement important de connaître effectivement tous les détails sur la façon de positionner les composants à la main. Laissons les outils appropriés le faire pour nous (Java est après tout conçu pour augmenter la productivité du programmeur).
t t t

The Swing event model

t

Le modèle d'événements de Swing

t t t
In the Swing event model a component can initiate (“fire”) an event. Each type of event is represented by a distinct class. When an event is fired, it is received by one or more “listeners,” which act on that event. Thus, the source of an event and the place where the event is handled can be separate. Since you typically use Swing components as they are, but need to write code that is called when the components receive an event, this is an excellent example of the separation of interface and implementation. t Dans le modèle d'événements de Swing, un composant peut initier (envoyer [fire]) un événement. Chaque type d'événement est représenté par une classe distincte. Lorsqu'un événement est envoyé, il est reçu par un ou plusieurs écouteurs [listeners], qui réagissent à cet événement. De ce fait, la source d'un événement et l'endroit où cet événement est traité peuvent être séparés. Puisqu'on utilise en général les composants Swing tels quels, mais qu'il faut écrire du code appelé lorsque les composants reçoivent un événement, ceci est un excellent exemple de la séparation de l'interface et de l'implémentation.
t t t
Each event listener is an object of a class that implements a particular type of listener interface. So as a programmer, all you do is create a listener object and register it with the component that’s firing the event. This registration is performed by calling an addXXXListener( ) method in the event-firing component, in which “XXX” represents the type of event listened for. You can easily know what types of events can be handled by noticing the names of the “addListener” methods, and if you try to listen for the wrong events you’ll discover your mistake at compile-time. You’ll see later in the chapter that JavaBeans also use the names of the “addListener” methods to determine what events a Bean can handle. t Chaque écouteur d'événements [event listener] est un objet d'une classe qui implémente une interface particulière de type listener. En tant que programmeur, il faut créer un objet listener et l'enregistrer avec le composant qui envoie l'événement. Cet enregistrement se fait par appel à une méthode addXXXListener() du composant envoyant l'événement, dans lequel XXX représente le type d'événement qu'on écoute.On peut facilement savoir quels types d'événements peuvent être gérés en notant les noms des méthodes addListener, et si on essaie d'écouter des événements erronés, l'erreur sera signalée à la compilation. On verra plus loin dans ce chapitre que les JavaBeans utilisent aussi les noms des méthodes addListener pour déterminer quels événements un Bean peut gérer.
t t t
All of your event logic, then, will go inside a listener class. When you create a listener class, the sole restriction is that it must implement the appropriate interface. You can create a global listener class, but this is a situation in which inner classes tend to be quite useful, not only because they provide a logical grouping of your listener classes inside the UI or business logic classes they are serving, but because (as you shall see later) the fact that an inner class object keeps a reference to its parent object provides a nice way to call across class and subsystem boundaries. t Toute notre logique des événements va se trouver dans une classe listener. Lorsqu'on crée une classe listener, la seule restriction est qu'elle doit implémenter l'interface appropriée. On peut créer une classe listener globale, mais on est ici dans un cas où les classes internes sont assez utiles, non seulement parce qu'elles fournissent un groupement logique de nos classes listener à l'intérieur des classes d'interface utilisateur ou de logique métier qu'elles desservent, mais aussi (comme on le verra plus tard) parce que le fait qu'un objet d'une classe interne garde une référence à son objet parent fournit une façon élégante d'appeler à travers les frontières des classes et des sous-systèmes.
t t t
All the examples so far in this chapter have been using the Swing event model, but the remainder of this section will fill out the details of that model.
t Jusqu'ici, tous les exemples de ce chapitre ont utilisé le modèle d'événements Swing, mais le reste de cette section va préciser les détails de ce modèle.
t t t

Event and listener types

t

Evénements et types de listeners

t t t
All Swing components include addXXXListener( ) and removeXXXListener( ) methods so that the appropriate types of listeners can be added and removed from each component. You’ll notice that the “XXX” in each case also represents the argument for the method, for example: addMyListener(MyListener m). The following table includes the basic associated events, listeners, and methods, along with the basic components that support those particular events by providing the addXXXListener( ) and removeXXXListener( ) methods. You should keep in mind that the event model is designed to be extensible, so you may encounter other events and listener types that are not covered in this table. t Chaque composant Swing contient des méthodes addXXXListener() et removeXXXListener() de manière à ce que les types de listeners adéquats puissent être ajoutés et enlevés de chaque composant. On remarquera que le XXX dans chaque cas représente également l'argument de cette méthode, par exemple : addMyListener(MyListener m). Le tableau suivant contient les événements, listeners et méthodes de base associées aux composants de base qui supportent ces événements particuliers en fournissant les méthodes addXXXListener() et removeXXXListener(). Il faut garder en tête que le modèle d'événements est destiné à être extensible, et donc on pourra rencontrer d'autres types d'événements et de listeners non couverts par ce tableau.
t t t
Event, listener interface and add- and remove-methods Components supporting this event
ActionEvent
ActionListener
addActionListener( )
removeActionListener( )
JButton, JList, JTextField, JMenuItem and its derivatives including JCheckBoxMenuItem, JMenu, and JpopupMenu.
AdjustmentEvent
AdjustmentListener
addAdjustmentListener( )
removeAdjustmentListener( )
JScrollbar
and anything you create that implements the Adjustable interface.
ComponentEvent
ComponentListener
addComponentListener( )
removeComponentListener( )
*Component and its derivatives, including JButton, JCanvas, JCheckBox, JComboBox, Container, JPanel, JApplet, JScrollPane, Window, JDialog, JFileDialog, JFrame, JLabel, JList, JScrollbar, JTextArea, and JTextField.
ContainerEvent
ContainerListener
addContainerListener( )
removeContainerListener( )
Container and its derivatives, including JPanel, JApplet, JScrollPane, Window, JDialog, JFileDialog, and JFrame.
FocusEvent
FocusListener
addFocusListener( )
removeFocusListener( )
Component and derivatives*.
KeyEvent
KeyListener
addKeyListener( )
removeKeyListener( )
Component and derivatives*.
MouseEvent (for both clicks and motion)
MouseListener
addMouseListener( )
removeMouseListener( )
Component and derivatives*.
MouseEvent[68] (for both clicks and motion)
MouseMotionListener
addMouseMotionListener( )
removeMouseMotionListener( )
Component and derivatives*.
WindowEvent
WindowListener
addWindowListener( )
removeWindowListener( )
Window and its derivatives, including JDialog, JFileDialog, and JFrame.
ItemEvent
ItemListener
addItemListener( )
removeItemListener( )
JCheckBox, JCheckBoxMenuItem, JComboBox, JList, and anything that implements the ItemSelectable interface.
TextEvent
TextListener
addTextListener( )
removeTextListener( )
Anything derived from JTextComponent, including JTextArea and JTextField.
t
Evénement, interface listener et méthodes add et remove Composants supportant cet événement
ActionEvent ActionListener addActionListener() removeActionListener() JButton, JList, JTextField, JMenuItem et ses dérivés, comprenant JCheckBoxMenuItem, JMenu, et JpopupMenu.
AdjustmentEvent AdjustmentListener addAdjustmentListener() removeAdjustmentListener() JScrollbar et tout ce qu'on crée qui implémente l'interface Adjustable.
ComponentEvent ComponentListener addComponentListener() removeComponentListener() *Component et ses dérivés, comprenant JButton, JCanvas, JCheckBox, JComboBox, Container, JPanel, JApplet, JScrollPane, Window, JDialog, JFileDialog, JFrame, JLabel, JList, JScrollbar, JTextArea, et JTextField.
ContainerEvent ContainerListener addContainerListener() removeContainerListener() Container et ses dérivés, comprenant JPanel, JApplet, JScrollPane, Window, JDialog, JFileDialog, et JFrame.
FocusEvent FocusListener addFocusListener() removeFocusListener() Component et dérivés*.
KeyEvent KeyListener addKeyListener() removeKeyListener() Component et dérivés*.
MouseEvent (à la fois pour les clics et pour le déplacement) MouseListener addMouseListener() removeMouseListener() Component et dérivés*.
MouseEvent [68](à la fois pour les clics et pour le déplacement) MouseMotionListener addMouseMotionListener() removeMouseMotionListener() Component et dérivés*.
WindowEvent WindowListener addWindowListener() removeWindowListener() Window et ses dérivés, comprenant JDialog, JFileDialog, and JFrame.
ItemEvent ItemListener addItemListener() removeItemListener() JCheckBox, JCheckBoxMenuItem, JComboBox, JList, et tout ce qui implémente l'interface ItemSelectable.
TextEvent TextListener addTextListener() removeTextListener() Tout ce qui est dérivé de JTextComponent, comprenant JTextArea et JTextField.
t t t
You can see that each type of component supports only certain types of events. It turns out to be rather difficult to look up all the events supported by each component. A simpler approach is to modify the ShowMethodsClean.java program from Chapter 12 so that it displays all the event listeners supported by any Swing component that you enter. t On voit que chaque type de composant ne supporte que certains types d'événements. Il semble assez difficile de rechercher tous les événements supportés par chaque composant. Une approche plus simple consiste à modifier le programme ShowMethodsClean.java du chapitre 12 de manière à ce qu'il affiche tous les event listeners supportés par tout composant Swing entré.
t t t
Chapter 12 introduced reflection and used that feature to look up methods for a particular class—either the entire list of methods or a subset of those whose names match a keyword that you provide. The magic of this is that it can automatically show you all the methods for a class without forcing you to walk up the inheritance hierarchy examining the base classes at each level. Thus, it provides a valuable timesaving tool for programming: because the names of most Java methods are made nicely verbose and descriptive, you can search for the method names that contain a particular word of interest. When you find what you think you’re looking for, check the online documentation. t Le chapitre 12 a introduit la réflexion et a utilisé cette fonctionnalité pour rechercher les méthodes d'une classe donnée, soit une liste complète des méthodes, soit un sous-ensemble des méthodes dont le nom contient un mot-clé donné. La magie dans ceci est qu'il peut automatiquement nous montrer toutes les méthodes d'une classe sans qu'on soit obligé de parcourir la hiérarchie des héritages en examinant les classes de base à chaque niveau. De ce fait, il fournit un outil précieux permettant de gagner du temps pour la programmation : comme les noms de la plupart des méthodes Java sont parlants et descriptifs, on peut rechercher les noms de méthodes contenant un mot particulier. Lorsqu'on pense avoir trouvé ce qu'on cherchait, il faut alors vérifier la documentation en ligne.
t t t
However, by Chapter 12 you hadn’t seen Swing, so the tool in that chapter was developed as a command-line application. Here is the more useful GUI version, specialized to look for the “addListener” methods in Swing components: t Comme dans le chapitre 12 on n'avait pas encore vu Swing, l'outil de ce chapitre était une application de ligne de commande. En voici une version plus pratique avec interface graphique, spécialisée dans la recherche des méthodes addListener dans les composants Swing :
t t t
//: c13:ShowAddListeners.java // Display the "addXXXListener" methods of any // Swing class. // <applet code = ShowAddListeners // width=500 height=400></applet> import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.lang.reflect.*; import java.io.*; import com.bruceeckel.swing.*; import com.bruceeckel.util.*; public class ShowAddListeners extends JApplet { Class cl; Method[] m; Constructor[] ctor; String[] n = new String[0]; JTextField name = new JTextField(25); JTextArea results = new JTextArea(40, 65); class NameL implements ActionListener { public void actionPerformed(ActionEvent e) { String nm = name.getText().trim(); if(nm.length() == 0) { results.setText("No match"); n = new String[0]; return; } try { cl = Class.forName("javax.swing." + nm); } catch(ClassNotFoundException ex) { results.setText("No match"); return; } m = cl.getMethods(); // Convert to an array of Strings: n = new String[m.length]; for(int i = 0; i < m.length; i++) n[i] = m[i].toString(); reDisplay(); } } void reDisplay() { // Create the result set: String[] rs = new String[n.length]; int j = 0; for (int i = 0; i < n.length; i++) if(n[i].indexOf("add") != -1 && n[i].indexOf("Listener") != -1) rs[j++] = n[i].substring(n[i].indexOf("add")); results.setText(""); for (int i = 0; i < j; i++) results.append( StripQualifiers.strip(rs[i]) + "\n"); } public void init() { name.addActionListener(new NameL()); JPanel top = new JPanel(); top.add(new JLabel( "Swing class name (press ENTER):")); top.add(name); Container cp = getContentPane(); cp.add(BorderLayout.NORTH, top); cp.add(new JScrollPane(results)); } public static void main(String[] args) { Console.run(new ShowAddListeners(), 500,400); } } ///:~ t
//: c13:ShowAddListeners.java
// Affiche les methodes "addXXXListener"
// d'une classe Swing donnee.
// <applet code = ShowAddListeners
// width=500 height=400></applet>
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import java.io.*;
import com.bruceeckel.swing.*;
import com.bruceeckel.util.*;

public class ShowAddListeners extends JApplet {
  Class cl;
  Method[] m;
  Constructor[] ctor;
  String[] n = new String[0];
  JTextField name = new JTextField(25);
  JTextArea results = new JTextArea(40, 65);
  class NameL implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      String nm = name.getText().trim();
      if(nm.length() == 0) {
        results.setText("No match");
        n = new String[0];
        return;
      }
      try {
        cl = Class.forName("javax.swing." + nm);
      } catch(ClassNotFoundException ex) {
        results.setText("No match");
        return;
      }
      m = cl.getMethods();
      // Conversion en un tableau de Strings :
      n = new String[m.length];
      for(int i = 0; i         n[i] = m[i].toString();
      reDisplay();
    }
  }
  void reDisplay() {
    // Creation de l'ensemble des resultats :
    String[] rs = new String[n.length];
    int j = 0;
    for (int i = 0; i       if(n[i].indexOf("add") != -1 &&
        n[i].indexOf("Listener") != -1)
          rs[j++] =
            n[i].substring(n[i].indexOf("add"));
    results.setText("");
    for (int i = 0; i       results.append(
        StripQualifiers.strip(rs[i]) + "\n");
  }
  public void init() {
    name.addActionListener(new NameL());
    JPanel top = new JPanel();
    top.add(new JLabel(
      "Swing class name (press ENTER):"));
    top.add(name);
    Container cp = getContentPane();
    cp.add(BorderLayout.NORTH, top);
    cp.add(new JScrollPane(results));
  }
  public static void main(String[] args) {
    Console.run(new ShowAddListeners(), 500,400);
  }
} ///:~
t t t
The StripQualifiers class defined in Chapter 12 is reused here by importing the com.bruceeckel.util library. t La classe StripQualifiers définie au chapitre 12 est réutilisée ici en important la bibliothèque com.bruceeckel.util.
t t t
The GUI contains a JTextField name in which you can enter the Swing class name you want to look up. The results are displayed in a JTextArea. t L'interface utilisateur graphique contient un JTextField name dans lequel on saisit le nom de la classe Swing à rechercher. Les résultats sont affichés dans une JTextArea.
t t t
You’ll notice that there are no buttons or other components by which to indicate that you want the search to begin. That’s because the JTextField is monitored by an ActionListener. Whenever you make a change and press ENTER, the list is immediately updated. If the text isn’t empty, it is used inside Class.forName( ) to try to look up the class. If the name is incorrect, Class.forName( ) will fail, which means that it throws an exception. This is trapped and the JTextArea is set to “No match.” But if you type in a correct name (capitalization counts), Class.forName( ) is successful and getMethods( ) will return an array of Method objects. Each of the objects in the array is turned into a String via toString( ) (this produces the complete method signature) and added to n, a String array. The array n is a member of class ShowAddListeners and is used in updating the display whenever reDisplay( ) is called. t On remarquera qu'il n'y a pas de boutons ou autres composants pour indiquer qu'on désire lancer la recherche. C'est parce que le JTextField est surveillé par un ActionListener. Lorsqu'on y fait un changement suivi de ENTER, la liste est immédiatement mise à jour. Si le texte n'est pas vide, il est utilisé dans Class.forName() pour rechercher la classe. Si le nom est incorrect, Class.forName() va échouer, c'est à dire qu'il va émettre une exception. Celle-ci est interceptée et le JTextArea est positionné à "No match". Mais si on tape un nom correct (les majuscules/minuscules comptent), Class.forName() réussit et getMethods() retourne un tableau d'objets Method. Chacun des objets du tableau est transformé en String à l'aide de toString() (cette méthode fournit la signature complète de la méthode) et ajoutée à n, un tableau de Strings. Le tableau n est un membre de la classe ShowAddListeners et est utilisé pour mettre à jour l'affichage chaque fois que reDisplay() est appelé.
t t t
reDisplay( ) creates an array of String called rs (for “result set”). The result set is conditionally copied from the Strings in n that contain “add” and “Listener.” indexOf( ) and substring( ) are then used to remove the qualifiers like public, static, etc. Finally, StripQualifiers.strip( ) removes the extra name qualifiers. t reDisplay() crée un tableau de Strings appelé rs (pour "result set" : ensemble de résultats). L'ensemble des résultats est conditionnellement copié depuis les Strings de n qui contiennent add et Listener. indexOf() et substring() sont ensuite utilisés pour enlever les qualificatifs tels que public, static, etc. Enfin, StripQualifiers.strip() enlève les qualificatifs de noms.
t t t
This program is a convenient way to investigate the capabilities of a Swing component. Once you know which events a particular component supports, you don’t need to look anything up to react to that event. You simply: t Ce programme est une façon pratique de rechercher les capacités d'un composant Swing. Une fois connus les événements supportés par un composant donné, il n'y a pas besoin de rechercher autre chose pour réagir à cet événement. Il suffit de :
t t t
  1. Take the name of the event class and remove the word “Event.” Add the word “Listener” to what remains. This is the listener interface you must implement in your inner class.
  2. Implement the interface above and write out the methods for the events you want to capture. For example, you might be looking for mouse movements, so you write code for the mouseMoved( ) method of the MouseMotionListener interface. (You must implement the other methods, of course, but there’s often a shortcut for that which you’ll see soon.)
  3. Create an object of the listener class in Step 2. Register it with your component with the method produced by prefixing “add” to your listener name. For example, addMouseMotionListener( ).
t
  1. Prendre le nom de la classe événement et retirer le mot Event. Ajouter le mot Listener à ce qui reste. Ceci donne le nom de l'interface listener qu'on doit implémenter dans une classe interne.
  2. Implémenter l'interface ci-dessus et écrire les méthodes pour les événements qu'on veut intercepter. Par exemple, on peut rechercher les événements de déplacement de la souris, et on écrit donc le code pour la méthode mouseMoved() de l'interface MouseMotionListener (il faut également implémenter les autres méthodes, bien sûr, mais il y a souvent un raccourci que nous verrons bientôt).
  3. Créer un objet de la classe listener de l'étape 2. L'enregistrer avec le composant avec la méthode dont le nom est fourni en ajoutant add au début du nom du listener. Par exemple, addMouseMotionListener().
t t t
Here are some of the listener interfaces: t Voici quelques-unes des interfaces listeners :
t t t
t t t
t t
\\\
///
t t t
t
     
Sommaire Le site de Bruce Eckel