t
t
t
t
t t 13) Création de fenêtres & d'Applets
tttt
13) Création de fenêtres & d'Applets
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



Exercises


t

Exercices

t t t
Solutions to selected exercises
can be found in the electronic document The Thinking in Java Annotated
Solution Guide
, available for a small fee from
www.BruceEckel.com.
t Les solutions des exercices sélectionnés se trouvent dans le document électronique The Thinking in Java Annotated Solution Guide, disponible pour une faible somme depuis www.BruceEckel.com.
t t t
  1. Create an
    applet/application using the Console class as shown in this chapter.
    Include a text field and three buttons. When you press each button, make some
    different text appear in the text
    field.
  2. Add a check
    box to the applet created in Exercise 1, capture the event, and insert different
    text into the text
    field.
  3. Create an
    applet/application using Console. In the HTML documentation from
    java.sun.com, find the JPasswordField and add this to the program.
    If the user types in the correct password, use Joptionpane to provide a
    success message to the
    user.
  4. Create an
    applet/application using Console, and add all the components that have an
    addActionListener( ) method. (Look these up in the HTML
    documentation from java.sun.com. Hint: use the index.) Capture their
    events and display an appropriate message for each inside a text
    field.
  5. Create an
    applet/application using Console, with a JButton and a
    JTextField
    . Write and attach the appropriate listener so that if the button
    has the focus, characters typed into it will appear in the
    JTextField
    .
  6. Create
    an applet/application using Console. Add to the main frame all the
    components described in this chapter, including menus and a dialog
    box.
  7. Modify
    TextFields.java so that the characters in t2 retain the original
    case that they were typed in, instead of automatically being forced to upper
    case.
  8. Locate and
    download one or more of the free GUI builder development environments available
    on the Internet, or buy a commercial product. Discover what is necessary to add
    BangBean to this environment and to use
    it.
  9. Add
    Frog.class to the manifest file as shown in this chapter and run
    jar to create a JAR file containing both Frog and BangBean.
    Now either download and install the BDK from Sun or use your own Beans-enabled
    program builder tool and add the JAR file to your environment so you can test
    the two
    Beans.
  10. Create your
    own JavaBean called Valve that contains two properties: a boolean
    called “on” and an int called “level.” Create a
    manifest file, use jar to package your Bean, then load it into the
    beanbox or into a Beans-enabled program builder tool so that you can test
    it.
  11. Modify
    MessageBoxes.java so that it has an individual ActionListener for
    each button (instead of matching the button
    text).
  12. Monitor a new
    type of event in TrackEvent.java by adding the new event handling code.
    You’ll need to discover on your own the type of event that you want to
    monitor.
  13. Inherit a
    new type of button from JButton. Each time you press this button, it
    should change its color to a randomly-selected value. See ColorBoxes.java
    in Chapter 14 for an example of how to generate a random color
    value.
  14. Modify
    TextPane.java to use a JTextArea instead of a
    JTextPane.
  15. Modify
    Menus.java to use radio buttons instead of check boxes on the
    menus.
  16. Simplify
    List.java by passing the array to the constructor and eliminating the
    dynamic addition of elements to the
    list.
  17. Modify
    SineWave.java to turn SineDraw into a JavaBean by adding
    “getter” and “setter”
    methods.
  18. Remember
    the “sketching box” toy with two knobs, one that controls the
    vertical movement of the drawing point, and one that controls the horizontal
    movement? Create one of those, using SineWave.java to get you started.
    Instead of knobs, use sliders. Add a button that will erase the entire
    sketch.
  19. Create an
    “asymptotic progress indicator” that gets slower and slower as it
    approaches the finish point. Add random erratic behavior so it will periodically
    look like it’s starting to speed
    up.
  20. Modify
    Progress.java so that it does not share models, but instead uses a
    listener to connect the slider and progress
    bar.
  21. Follow the
    instructions in the section titled “Packaging an applet into a JAR
    file” to place TicTacToe.java into a JAR file. Create an HTML page
    with the (messy, complicated) version of the applet tag, and modify it to use
    the archive tag so as to use the JAR file. (Hint: start with the HTML page for
    TicTacToe.java that comes with this book’s source-code
    distribution.)
  22. Create
    an applet/application using Console. This should have three sliders, one
    each for the red, green, and blue values in java.awt.Color. The rest of
    the form should be a JPanel that displays the color determined by the
    three sliders. Also include non-editable text fields that show the current RGB
    values.
  23. In the HTML
    documentation for javax.swing, look up the JColorChooser. Write a
    program with a button that brings up the color chooser as a
    dialog.
  24. Almost every
    Swing component is derived from Component, which has a
    setCursor( ) method. Look this up in the Java HTML documentation.
    Create an applet and change the cursor to one of the stock cursors in the
    Cursor
    class.
  25. Starting with
    ShowAddListeners.java, create a program with the full functionality of
    ShowMethodsClean.java from Chapter
    12.

t
  1. Créer une applet/application utilisant la classe Console comme montré dans ce chapitre. Inclure un champ texte et trois boutons. Lorsqu'on appuie sur chaque bouton, faire afficher un texte différent dans le champ texte.
  2. Ajouter une boîte à cocher à l'applet de l'exercice 1, capturer l'événement, et insérer un texte différent dans le champ texte.
  3. Créer une applet/application utilisant Console. Dans la documentation HTML de java.sun.com, trouver le JPasswordField et l'ajouter à ce programme. Si l'utilisateur tape le mot de passe correct, utiliser JOptionPane pour fournir un message de succès à l'utilisateur.
  4. Créer une applet/application utilisant Console, et ajouter tous les composants qui ont une méthode addActionListener() (rechercher celles-ci dans la documentation HTML de java.sun.com; conseil : utiliser l'index). Capturer ces événements et afficher un message approprié pour chacun dans un champ texte.
  5. Créer une applet/application utilisant Console, avec un JButton et un JTextField. Ecrire et attacher le listener approprié de sorte que si le bouton a le focus, les caractères tapés dessus apparaissent dans le JTextField.
  6. Créer une applet/application utilisant Console. Ajouter à la fenêtre principale tous les composants décrits dans ce chapitre, y compris les menus et une boîte de dialogue.
  7. Modifier TextFields.java de sorte que les caractères de t2 gardent la casse qu'ils avaient lorsqu'ils ont été tapés, plutôt que les forcer automatiquement en majuscules.
  8. Rechercher et télécharger un ou plusieurs des environnements de développement de GUI disponibles sur Internet, ou acheter un produit du commerce. Découvrir ce qu'il faut faire pour ajouter Bangbean à cet environnement et pour l'utiliser.
  9. Ajouter Frog.class au fichier manifest comme montré dans ce chapitre, et lancer jar pour créer un fichier JAR contenant à la fois Frog et BangBean. Ensuite, télécharger et installer le BDK de Sun ou utiliser un outil de développement admettant les Beans et ajouter le fichier JAR à votre environnement de manière à pouvoir tester les deux Beans.
  10. Créer un JavaBean appelé Valve qui contient deux propriétés : un boolean appelé on et un int appelé level. Créer un fichier manifest, utiliser jar pour empaqueter le Bean, puis le charger dans la beanbox ou dans un outil de développement acceptant les Beans, de manière à pouvoir le tester.
  11. Modifier MessageBoxes.java de manière à ce qu'il ait un ActionListener individuel pour chaque bouton (au lieu d'un correspondant au texte du bouton).
  12. Surveiller un nouveau type d'événement dans TrackEvent.java en ajoutant le nouveau code de traitement de l'événement. Il faudra découvrir vous-même le type d'événement que vous voulez surveiller.
  13. Créer un nouveau type de bouton hérité de JButton. Chaque fois qu'on appuie sur le bouton, celui-ci doit modifier sa couleur selon une couleur choisie de façon aléatoire. Voir ColorBoxes.java au Chapitre 14 pour un exemple de la manière de générer aléatoirement une valeur de couleur.
  14. Modifier TextPane.java de manière à utiliser un JTextArea à la place du JTextPane.
  15. Modifier Menus.java pour utiliser des boutons radio au lieu de boîtes à cocher dans les menus.
  16. Simplifier List.java en passant le tableau au constructeur et en éliminant l'ajout dynamique d'éléments à la liste.
  17. Modifier SineWave.java pour transformer SineDraw en JavaBean en lui ajoutant des méthodes get et set.
  18. Vous vous souvenez du jouet permettant de faire des dessins avec deux boutons, un qui contrôle le mouvement vertical, et un qui contrôle le mouvement horizontal ? En créer un, en utilisant SineWave.java comme point de départ. A la place des boutons, utiliser des curseurs. Ajouter un bouton d'effacement de l'ensemble du dessin.
  19. Créer un indicateur de progression asymptotique qui ralentit au fur et à mesure qu'il s'approche de la fin. Ajouter un comportement aléatoire de manière à donner l'impression qu'il se remet à accélérer.
  20. Modifier Progress.java de manière à utiliser un listener plutôt que le partage du modèle pour connecter le curseur et la barre de progression.
  21. Suivre les instructions du paragraphe «Empaquetage d'une applet dans un fichier JAR» pour placer TicTacToe.java dans un fichier JAR. Créer une page HTML avec la version brouillonne et compliquée du tag applet, et la modifier pour utiliser le tag archive de manière à utiliser le fichier JAR (conseil : commencer par utiliser la page HTML pour TicTacToe.java qui est fournie avec le code source pour ce livre).
  22. Créer une applet/application utilisant Console. Celle-ci doit avoir trois curseurs, un pour le rouge, un pour le vert et un pour le bleu de java.awt.Color. Le reste du formulaire sera un JPanel qui affiche la couleur fixée par les trois curseurs. Ajouter également des champs textes non modifiables qui indiquent les valeurs courantes des valeurs RGB.
  23. Dans la documentation HTML de javax.swing, rechercher le JColorChooser. Ecrire un programme avec un bouton qui ouvre le sélectionneur de couleur comme un dialogue.
  24. Presque tous les composants Swing sont dérivés de Component, qui a une méthode setCursor(). Rechercher ceci dans la documentation HTML Java . Créer une applet et modifier le curseur selon un des curseurs disponibles dans la classe Cursor.
  25. En prenant comme base ShowAddListeners.java, créer un programme avec toutes les fonctionnalités de ShowMethodsClean.java du Chapitre 12.
t t t
[61]
A variation on this is called “the principle of least astonishment,”
which essentially says: “don’t surprise the
user.”
t [61] Une variante est appelée le principe de l'étonnement minimum, qui dit essentiellement : «ne pas surprendre l'utilisateur».
t t t
[62]
This is an example of the design pattern called the template
method
.
t [62] Ceci est un exemple du modèle de conception [design pattern] appelé la méthode du modèle [template method].
t t t
[63]
It is assumed that the reader is familiar with the basics of HTML. It’s
not too hard to figure out, and there are lots of books and
resources.
t [63] On suppose que le lecteur connaît les bases du HTML. Il n'est pas très difficile à comprendre, et il y a beaucoup de livres et de ressources disponibles.
t t t
[64]
This page—in particular, the ‘clsid’ portion—seemed to
work fine with both JDK1.2.2 and JDK1.3 rc-1. However, you may find that you
have to change the tag sometime in the future. Details can be found at
java.sun.com.
t [64] Cette page (en particulier la partie clsid) semblait bien fonctionner avec le JDK1.2.2 et le JDK1.3rc-1. Cependant il se peut que vous ayez parfois besoin de changer le tag dans le futur. Des détails peuvent être trouvés à java.sun.com.
t t t
[65]
In my opinion. And after you learn about Swing, you won’t want to waste
your time on the earlier stuff.
t [65] Selon moi. Et après avoir étudié Swing, vous n'aurez plus envie de perdre votre temps sur les parties plus anciennes.
t t t
[66]
As described earlier, “Frame” was already taken by the AWT, so Swing
uses JFrame.
t [66] Comme décrit plus avant, Frame était déjà utilisé par AWT, de sorte que Swing utilise JFrame.
t t t
[67]
This will make sense after you’ve read further in this chapter. First,
make the reference JApplet a static member of the class (instead
of a local variable of main( )), and then call
applet.stop( ) and applet.destroy( ) inside
WindowAdapter.windowClosing( ) before you call
System.exit( ).
t [67] Ceci s'éclaircira après avoir avancé dans ce chapitre. D'abord faire de la référence JApplet un membre static de la classe (au lieu d'une variable locale de main()), et ensuite appeler applet.stop() et applet.destroy() dans WindowAdapter.windowClosing() avant d'appeler System.exit().
t t t
[68]
There is no MouseMotionEvent even though it seems like there ought to be.
Clicking and motion is combined into MouseEvent, so this second
appearance of MouseEvent in the table is not an error.
t [68] Il n'y a pas de MouseMotionEvent bien qu'il semble qu'il devrait y en avoir un. Le cliquage et le déplacement sont combinés dans MouseEvent, de sorte que cette deuxième apparition de MouseEvent dans le tableau n'est pas une erreur.
t t t
[69]
In Java 1.0/1.1 you could not usefully inherit from the button object.
This was only one of numerous fundamental design flaws.


    
     [ Previous Chapter ]
    [ Short TOC ]
    [ Table of Contents ]
    [ Index ]
     [ Next Chapter ]
    
    
Last Update:04/24/2000
t [69] En Java 1.0/1.1 on ne pouvait pas hériter de l'objet bouton de façon exploitable. C'était un des nombreux défauts de conception.
t t t
t t t
t t
\\\
    
t t t
t
     
Sommaire Le site de Bruce Eckel