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
Creating a JTextField and placing it on the canvas takes the same steps as for JButtons, or for any Swing component. The difference in the above program is in the creation of the aforementioned ActionListener class BL. The argument to actionPerformed( ) is of type ActionEvent, which contains all the information about the event and where it came from. In this case, I wanted to describe the button that was pressed: getSource( ) produces the object where the event originated, and I assumed that is a JButton. getText( ) returns the text that’s on the button, and this is placed in the JTextField to prove that the code was actually called when the button was pressed. t La création d'un JTextField et son placement sur la surface comprend les mêmes opérations que pour les JButtons, comme pour tout composant Swing. La différence dans le programme ci-dessus est la création de la classe BL de type ActionListener mentionnée précédemment. L'argument de actionPerformed() est du type ActionEvent, qui contient toute l'information sur l'événement et d'où il vient. Dans ce cas, je voulais décrire le bouton qui a été enfoncé : getSource() fournit l'objet d'où l'événement est issu, et j'ai supposé que c'était un JButton. getText() retourne le texte qui est sur le bouton, qui est placé dans le JTextField pour prouver que le code a bien été appelé quand le bouton a été enfoncé.
t t t
In init( ), addActionListener( ) is used to register the BL object with both the buttons. t Dans init(), addActionListener() est utilisée pour enregistrer l'objet BL pour chacun des boutons.
t t t
It is often more convenient to code the ActionListener as an anonymous inner class, especially since you tend to only use a single instance of each listener class. Button2.java can be modified to use an anonymous inner class as follows: t Il est souvent plus pratique de coder l'ActionListener comme une classe anonyme interne [anonymous inner class], particulièrement lorsqu'on a tendance à n'utiliser qu'une seule instance de chaque classe listener. Button2.java peut être modifié de la façon suivante pour utiliser une classe interne anonyme :
t t t
//: c13:Button2b.java // Using anonymous inner classes. // <applet code=Button2b width=200 height=75> // </applet> import javax.swing.*; import java.awt.event.*; import java.awt.*; import com.bruceeckel.swing.*; public class Button2b extends JApplet { JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2"); JTextField txt = new JTextField(10); ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e){ String name = ((JButton)e.getSource()).getText(); txt.setText(name); } }; public void init() { b1.addActionListener(al); b2.addActionListener(al); Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(b1); cp.add(b2); cp.add(txt); } public static void main(String[] args) { Console.run(new Button2b(), 200, 75); } } ///:~ t
//: c13:Button2b.java
// Utilisation de classes anonymes internes.
// <applet code=Button2b width=200 height=75>
// </applet>
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import com.bruceeckel.swing.*;

public class Button2b extends JApplet {
JButton
  b1 = new JButton("Button 1"),
  b2 = new JButton("Button 2");
JTextField txt = new JTextField(10);
ActionListener al = new ActionListener() {
   public void actionPerformed(ActionEvent e){
    String name =
      ((JButton)e.getSource()).getText();
    txt.setText(name);
  }
};
  public void init() {
  b1.addActionListener(al);
  b2.addActionListener(al);
  Container cp = getContentPane();
  cp.setLayout(new FlowLayout());
  cp.add(b1);
  cp.add(b2);
  cp.add(txt);
}
  public static void main(String[] args) {
  Console.run(new Button2b(), 200, 75);
}
} ///:~
t t t
The approach of using an anonymous inner class will be preferred (when possible) for the examples in this book.
t L'utilisation d'une classe anonyme interne sera préférée (si possible) pour les exemples de ce livre.
t t t

Text areas

t

Zones de texte

t t t
A JTextArea is like a JTextField except that it can have multiple lines and has more functionality. A particularly useful method is append( ); with this you can easily pour output into the JTextArea, thus making a Swing program an improvement (since you can scroll backward) over what has been accomplished thus far using command-line programs that print to standard output. As an example, the following program fills a JTextArea with the output from the geography generator in Chapter 9: t Un JTextArea est comme un JTextField, sauf qu'il peut avoir plusieurs lignes et possède plus de fonctionnalités. Une méthode particulièrement utile est append(); avec cette méthode on peut facilement transférer une sortie dans un JTextArea, faisant de ce fait d'un programme Swing une amélioration (du fait qu'on peut scroller en arrière) par rapport à ce qui a été fait jusqu'ici en utilisant des programmes de ligne de commande qui impriment sur la sortie standard. Comme exemple, le programme suivant remplit un JTextArea avec la sortie du générateur geography du chapitre 9 :
t t t
//: c13:TextArea.java // Using the JTextArea control. // <applet code=TextArea width=475 height=425> // </applet> import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; import com.bruceeckel.swing.*; import com.bruceeckel.util.*; public class TextArea extends JApplet { JButton b = new JButton("Add Data"), c = new JButton("Clear Data"); JTextArea t = new JTextArea(20, 40); Map m = new HashMap(); public void init() { // Use up all the data: Collections2.fill(m, Collections2.geography, CountryCapitals.pairs.length); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ for(Iterator it= m.entrySet().iterator(); it.hasNext();){ Map.Entry me = (Map.Entry)(it.next()); t.append(me.getKey() + ": " + me.getValue() + "\n"); } } }); c.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ t.setText(""); } }); Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(new JScrollPane(t)); cp.add(b); cp.add(c); } public static void main(String[] args) { Console.run(new TextArea(), 475, 425); } } ///:~ t
//: c13:TextArea.java
// Utilisation du contrôle JTextArea.
// <applet code=TextArea width=475 height=425>
// </applet>
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import com.bruceeckel.swing.*;
import com.bruceeckel.util.*;

public class TextArea extends JApplet {
JButton
  b = new JButton("Add Data"),
  c = new JButton("Clear Data");
JTextArea t = new JTextArea(20, 40);
Map m = new HashMap();
  public void init() {
   // Utilisation de toutes les données :
  Collections2.fill(m,
    Collections2.geography,
    CountryCapitals.pairs.length);
  b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e){
      for(Iterator it= m.entrySet().iterator();
          it.hasNext();){
        Map.Entry me = (Map.Entry)(it.next());
        t.append(me.getKey() + ": "
          + me.getValue() + "\n");
      }
    }
  });
  c.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e){
      t.setText("");
    }
  });
  Container cp = getContentPane();
  cp.setLayonew FlowLayout());
  cp.add(new JScrollPane(t));
  cp.add(b);
  cp.add(c);
}
  public static void main(String[] args) {
  Console.run(new TextArea(), 475, 425);
}
} ///:~
t t t
In init( ), the Map is filled with all the countries and their capitals. Note that for both buttons the ActionListener is created and added without defining an intermediate variable, since you never need to refer to that listener again during the program. The “Add Data” button formats and appends all the data, while the “Clear Data” button uses setText( ) to remove all the text from the JTextArea. t Dans init(), le Map est rempli avec tous les pays et leurs capitales. Remarquons que pour chaque bouton l'ActionListener est créé et ajouté sans définir de variable intermédiaire, puisqu'on n'aura plus jamais besoin de s'y référer dans la suite du programme. Le bouton "Add Data" formate et ajoute à la fin toutes les données, tandis que le bouton "Clear Data" utilise setText() pour supprimer tout le texte du JTextArea.
t t t
As the JTextArea is added to the applet, it is wrapped in a JScrollPane, to control scrolling when too much text is placed on the screen. That’s all you must do in order to produce full scrolling capabilities. Having tried to figure out how to do the equivalent in some other GUI programming environments, I am very impressed with the simplicity and good design of components like JScrollPane.
t Lors de l'ajout du JTextArea à l'applet, il est enveloppé dans un JScrollPane, pour contrôler le scrolling quand trop de texte est placé à l'écran. C'est tout ce qu'il y a à faire pour fournir des fonctionnalités de scrolling complètes. Ayant essayé d'imaginer comment faire l'équivalent dans d'autres environnements de programmation de GUI, je suis très impressionné par la simplicité et la bonne conception de composants tels que le JScrollPane.
t t t

Controlling layout

t

Contrôle de la disposition

t t t
The way that you place components on a form in Java is probably different from any other GUI system you’ve used. First, it’s all code; there are no “resources” that control placement of components. Second, the way components are placed on a form is controlled not by absolute positioning but by a “layout manager” that decides how the components lie based on the order that you add( ) them. The size, shape, and placement of components will be remarkably different from one layout manager to another. In addition, the layout managers adapt to the dimensions of your applet or application window, so if the window dimension is changed, the size, shape, and placement of the components can change in response. t La façon dont on place les composants sur un formulaire en Java est probablement différente de tout système de GUI que vous avez utilisé. Premièrement, tout est dans le code ; il n'y a pas de ressources qui contrôlent le placement des composants. Deuxièmement, la façon dont les composants sont placés dans un formulaire est contrôlée non pas par un positionnement absolu mais par un layout manager qui décide comment les composants sont placés, selon l'ordre dans lequel on les ajoute ( add() ). La taille, la forme et le placement des composants seront notablement différents d'un layout manager à l'autre. De plus, les gestionnaires de disposition s'adaptent aux dimensions de l'applet ou de la fenêtre de l'application, de sorte que si la dimension de la fenêtre est changée, la taille, la forme et le placement des composants sont modifiés en conséquence.
t t t
JApplet, JFrame JWindow, and JDialog can all produce a Container with getContentPane( ) that can contain and display Components. In Container, there’s a method called setLayout( ) that allows you to choose a different layout manager. Other classes, such as JPanel, contain and display components directly and so you also set the layout manager directly, without using the content pane. t JApplet, JFrame, JWindow et JDialog peuvent chacun fournir un Container avec getContentPane() qui peut contenir et afficher des Components. Dans Container, il y a une méthode appelée setLayout() qui permet de choisir le layout manager. D'autres classes telles que JPanel contiennent et affichent des composants directement, et donc il faut leur imposer directement le layout manager, sans utiliser le content pane.
t t t
In this section we’ll explore the various layout managers by placing buttons in them (since that’s the simplest thing to do). There won’t be any capturing of button events since these examples are just intended to show how the buttons are laid out.
t Dans cette section nous allons explorer les divers gestionnaires de disposition en créant des boutons (puisque c'est ce qu'il y a de plus simple). Il n'y aura aucune capture d'événements de boutons puisque ces exemples ont pour seul but de montrer comment les boutons sont disposés.
t t t

BorderLayout

t

BorderLayout

t t t
The applet uses a default layout scheme: the BorderLayout (a number of the previous example have changed the layout manager to FlowLayout). Without any other instruction, this takes whatever you add( ) to it and places it in the center, stretching the object all the way out to the edges. t L'applet utilise un layout manager par défaut : le BorderLayout (certains des exemples précédents ont modifié le layout manager par défaut pour FlowLayout). Sans autre information, il prend tout ce qu'on lui ajoute ( add() ) et le place au centre, en étirant l'objet dans toutes les directions jusqu'aux bords.
t t t
However, there’s more to the BorderLayout. This layout manager has the concept of four border regions and a center area. When you add something to a panel that’s using a BorderLayout you can use the overloaded add( ) method that takes a constant value as its first argument. This value can be any of the following: t Cependant le BorderLayout ne se résume pas qu'à cela. Ce layout manager possède le concept d'une zone centrale et de quatre régions périphériques. Quand on ajoute quelque chose à un panel qui utilise un BorderLayout, on peut utiliser la méthode add() surchargée qui prend une valeur constante comme premier argument. Cette valeur peut être une des suivantes :
t t t
BorderLayout. NORTH (top)
BorderLayout. SOUTH (bottom)
BorderLayout. EAST (right)
BorderLayout. WEST (left)
BorderLayout.CENTER (fill the middle, up to the other components or to the edges)
t BorderLayout.NORTH (en haut) BorderLayout.SOUTH (en bas) BorderLayout.EAST (à droite) BorderLayout.WEST (à gauche) BorderLayout.CENTER (remplir le milieu, jusqu'aux autres composants ou jusqu'aux bords)
t t t
If you don’t specify an area to place the object, it defaults to CENTER. t Si aucune région n'est spécifiée pour placer l'objet, le défaut est CENTER.
t t t
Here’s a simple example. The default layout is used, since JApplet defaults to BorderLayout: t Voici un exemple simple. Le layout par défaut est utilisé, puisque JApplet a BorderLayout par défaut :
t t t
//: c13:BorderLayout1.java // Demonstrates BorderLayout. // <applet code=BorderLayout1 // width=300 height=250> </applet> import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class BorderLayout1 extends JApplet { public void init() { Container cp = getContentPane(); cp.add(BorderLayout.NORTH, new JButton("North")); cp.add(BorderLayout.SOUTH, new JButton("South")); cp.add(BorderLayout.EAST, new JButton("East")); cp.add(BorderLayout.WEST, new JButton("West")); cp.add(BorderLayout.CENTER, new JButton("Center")); } public static void main(String[] args) { Console.run(new BorderLayout1(), 300, 250); } } ///:~ t
//: c13:BorderLayout1.java
// Démonstration de BorderLayout.
// <applet code=BorderLayout1
// width=300 height=250> </applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;

public class BorderLayout1 extends JApplet {
  public void init() {
  Container cp = getContentPane();
  cp.add(BorderLayout.NORTH,
    new JButton("North"));
  cp.add(BorderLayout.SOUTH,
    new JButton("South"));
  cp.add(BorderLayout.EAST,
    new JButton("East"));
  cp.add(BorderLayout.WEST,
    new JButton("West"));
cp.add(BorderLayout.CENTER,
    new JButton("Center"));
}
  public static void main(String[] args) {
  Console.run(new BorderLayout1(), 300, 250);
}
} ///:~
t t t
For every placement but CENTER, the element that you add is compressed to fit in the smallest amount of space along one dimension while it is stretched to the maximum along the other dimension. CENTER, however, spreads out in both dimensions to occupy the middle.
t Pour chaque placement autre que CENTER, l'élément qu'on ajoute est comprimé pour tenir dans le plus petit espace le long d'une dimension et étiré au maximum le long de l'autre dimension. CENTER, par contre, s'étend dans chaque dimension pour occuper le milieu.
t t t

FlowLayout

t

FlowLayout

t t t
This simply “flows” the components onto the form, from left to right until the top space is full, then moves down a row and continues flowing. t Celui-ci aligne simplement les composants sur le formulaire, de gauche à droite jusqu'à ce que l'espace du haut soit rempli, puis descend d'une rangée et continue l'alignement.
t t t
Here’s an example that sets the layout manager to FlowLayout and then places buttons on the form. You’ll notice that with FlowLayout the components take on their “natural” size. A JButton, for example, will be the size of its string. t Voici un exemple qui positionne le layout manager en FlowLayout et place ensuite des boutons sur le formulaire. On remarquera qu'avec FlowLayout les composants prennent leur taille naturelle. Un JButton, par exemple, aura la taille de sa chaîne.
t t t
//: c13:FlowLayout1.java // Demonstrates FlowLayout. // <applet code=FlowLayout1 // width=300 height=250> </applet> import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class FlowLayout1 extends JApplet { public void init() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); for(int i = 0; i < 20; i++) cp.add(new JButton("Button " + i)); } public static void main(String[] args) { Console.run(new FlowLayout1(), 300, 250); } } ///:~ t
//: c13:FlowLayout1.java
// Démonstration de FlowLayout.
// <applet code=FlowLayout1
// width=300 height=250> </applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;

public class FlowLayout1 extends JApplet {
  public void init() {
  Container cp = getContentPane();
  cp.setLayout(new FlowLayout());
   for(int i = 0; i     cp.add(new JButton("Button " + i));
}
  public static void main(String[] args) {
  Console.run(new FlowLayout1(), 300, 250);
}
} ///:~
t t t
All components will be compacted to their smallest size in a FlowLayout, so you might get a little bit of surprising behavior. For example, because a JLabel will be the size of its string, attempting to right-justify its text yields an unchanged display when using FlowLayout.
t Tous les composants sont compactés à leur taille minimum dans un FlowLayout, ce qui fait qu'on peut parfois obtenir un comportement surprenant. Par exemple, vu qu'un JLabel prend la taille de sa chaîne, une tentative de justifier à droite son texte ne donne pas de modification de l'affichage dans un FlowLayout.
t t t

GridLayout

t

GridLayout

t t t
A GridLayout allows you to build a table of components, and as you add them they are placed left-to-right and top-to-bottom in the grid. In the constructor you specify the number of rows and columns that you need and these are laid out in equal proportions. t Un GridLayout permet de construire un tableau de composants, et lorsqu'on les ajoute ils sont placés de gauche à droite et de haut en bas dans la grille. Dans le constructeur on spécifie le nombre de rangées et de colonnes nécessaires, et celles-ci sont disposées en proportions identiques.
t t t
//: c13:GridLayout1.java // Demonstrates GridLayout. // <applet code=GridLayout1 // width=300 height=250> </applet> import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class GridLayout1 extends JApplet { public void init() { Container cp = getContentPane(); cp.setLayout(new GridLayout(7,3)); for(int i = 0; i < 20; i++) cp.add(new JButton("Button " + i)); } public static void main(String[] args) { Console.run(new GridLayout1(), 300, 250); } } ///:~ t
//: c13:GridLayout1.java
// Démonstration de GridLayout.
// <applet code=GridLayout1
// width=300 height=250> </applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;

public class GridLayout1 extends JApplet {
  public void init() {
  Container cp = getContentPane();
  cp.setLayout(new GridLayout(7,3));
   for(int i = 0; i     cp.add(new JButton("Button " + i));
}
  public static void main(String[] args) {
  Console.run(new GridLayout1(), 300, 250);
}
} ///:~
t t t
In this case there are 21 slots but only 20 buttons. The last slot is left empty because no “balancing” goes on with a GridLayout.
t Dans ce cas il y a 21 cases mais seulement 20 boutons. La dernière case est laissée vide car il n'y a pas d'équilibrage dans un GridLayout.
t t t

GridBagLayout

t

GridBagLayout

t t t
The GridBagLayout provides you with tremendous control in deciding exactly how the regions of your window will lay themselves out and reformat themselves when the window is resized. However, it’s also the most complicated layout manager, and quite difficult to understand. It is intended primarily for automatic code generation by a GUI builder (good GUI builders will use GridBagLayout instead of absolute placement). If your design is so complicated that you feel you need to use GridBagLayout, then you should be using a GUI builder tool to generate that design. If you feel you must know the intricate details, I’ll refer you to Core Java 2 by Horstmann & Cornell (Prentice-Hall, 1999), or a dedicated Swing book, as a starting point.
t Le GridBagLayoutnous donne un contrôle fin pour décider exactement comment les régions d'une fenêtre vont se positionner et se replacer lorsque la fenêtre est redimensionnée. Cependant, c'est aussi le plus compliqué des layout managers, et il est assez difficile à comprendre. Il est destiné principalement à la génération de code automatique par un constructeur d'interfaces utilisateurs graphiques [GUI builder] (les bons GUI builders utilisent GridBagLayout plutôt que le placement absolu). Si votre modèle est compliqué au point que vous sentiez le besoin d'utiliser le GridBagLayout, vous devrez dans ce cas utiliser un outil GUI builder pour générer ce modèle. Si vous pensez devoir en connaître les détails internes, je vous renvoie à Core Java 2 par Horstmann & Cornell (Prentice-Hall, 1999), ou un livre dédié à Swing, comme point de départ.
t t t

Absolute positioning

t

Positionnement absolu

t t t
It is also possible to set the absolute position of the graphical components in this way: t Il est également possible de forcer la position absolue des composants graphiques de la façon suivante :
t t t
  1. Set a null layout manager for your Container: setLayout(null).
  2. Call setBounds( ) or reshape( ) (depending on the language version) for each component, passing a bounding rectangle in pixel coordinates. You can do this in the constructor, or in paint( ), depending on what you want to achieve.
t
  1. Positionner un layout manager null pour le Container : setLayout(null).
  2. Appeler setBounds() ou reshape() (selon la version du langage) pour chaque composant, en passant un rectangle de limites avec ses coordonnées en pixels. Ceci peut se faire dans le constructeur, ou dans paint(), selon le but désiré.
t t t
Some GUI builders use this approach extensively, but this is usually not the best way to generate code. More useful GUI builders will use GridBagLayout instead.
t Certains GUI builders utilisent cette approche de manière extensive, mais ce n'est en général pas la meilleure manière de générer du code. Les GUI builders les plus efficaces utilisent plutôt GridBagLayout.
t t t

BoxLayout

t

BoxLayout

t t t
Because people had so much trouble understanding and working with GridBagLayout, Swing also includes the BoxLayout, which gives you many of the benefits of GridBagLayout without the complexity, so you can often use it when you need to do hand-coded layouts (again, if your design becomes too complex, use a GUI builder that generates GridBagLayouts for you). BoxLayout allows you to control the placement of components either vertically or horizontally, and to control the space between the components using something called “struts and glue.” First, let’s see how to use the BoxLayout directly, in the same way that the other layout managers have been demonstrated: t Les gens ayant tellement de problèmes pour comprendre et utiliser GridBagLayout, Swing contient également le BoxLayout, qui offre la plupart des avantages du GridBagLayout sans en avoir la complexité, de sorte qu'on peut souvent l'utiliser lorsqu'on doit coder à la main des layouts (encore une fois, si votre modèle devient trop compliqué, utilisez un GUI builder qui générera les GridBagLayouts à votre place). BoxLayout permet le contrôle du placement des composants soit verticalement soit horizontalement, et le contrôle de l'espace entre les composants en utilisant des choses appelées struts (entretoises) et glue (colle). D'abord, voyons comment utiliser BoxLayout directement, en faisant le même genre de démonstration que pour les autres layout managers :
t t t
//: c13:BoxLayout1.java // Vertical and horizontal BoxLayouts. // <applet code=BoxLayout1 // width=450 height=200> </applet> import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class BoxLayout1 extends JApplet { public void init() { JPanel jpv = new JPanel(); jpv.setLayout( new BoxLayout(jpv, BoxLayout.Y_AXIS)); for(int i = 0; i < 5; i++) jpv.add(new JButton("" + i)); JPanel jph = new JPanel(); jph.setLayout( new BoxLayout(jph, BoxLayout.X_AXIS)); for(int i = 0; i < 5; i++) jph.add(new JButton("" + i)); Container cp = getContentPane(); cp.add(BorderLayout.EAST, jpv); cp.add(BorderLayout.SOUTH, jph); } public static void main(String[] args) { Console.run(new BoxLayout1(), 450, 200); } } ///:~ t
//: c13:BoxLayout1.java
// BoxLayouts vertical et horizontal.
// <applet code=BoxLayout1
// width=450 height=200> </applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;

public class BoxLayout1 extends JApplet {
  public void init() {
  JPanel jpv = new JPanel();
  jpv.setLayout(
    new BoxLayout(jpv, BoxLayout.Y_AXIS));
   for(int i = 0; i     jpv.add(new JButton("" + i));
  JPanel jph = new JPanel();
  jph.setLayout(
    new BoxLayout(jph, BoxLayout.X_AXIS));
   for(int i = 0; i     jph.add(new JButton("" + i));
  Container cp = getContentPane();
  cp.add(BorderLayout.EAST, jpv);
  cp.add(BorderLayout.SOUTH, jph);
}
  public static void main(String[] args) {
  Console.run(new BoxLayout1(), 450, 200);
}
} ///:~
t t t
The constructor for BoxLayout is a bit different than the other layout managers—you provide the Container that is to be controlled by the BoxLayout as the first argument, and the direction of the layout as the second argument. t Le constructeur du BoxLayout est un peu différent des autres layout managers : on fournit le Container que le BoxLayout doit contrôler comme premier argument, et la direction du layout comme deuxième argument.
t t t
To simplify matters, there’s a special container called Box that uses BoxLayout as its native manager. The following example lays out components horizontally and vertically using Box, which has two static methods to create boxes with vertical and horizontal alignment: t Pour simplifier les choses, il y a un container spécial appelé Box qui utilise BoxLayout comme manager d'origine. L'exemple suivant place les composants horizontalement et verticalement en utilisant Box, qui possède deux méthodes static pour créer des boxes avec des alignements verticaux et horizontaux :
t t t
//: c13:Box1.java // Vertical and horizontal BoxLayouts. // <applet code=Box1 // width=450 height=200> </applet> import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class Box1 extends JApplet { public void init() { Box bv = Box.createVerticalBox(); for(int i = 0; i < 5; i++) bv.add(new JButton("" + i)); Box bh = Box.createHorizontalBox(); for(int i = 0; i < 5; i++) bh.add(new JButton("" + i)); Container cp = getContentPane(); cp.add(BorderLayout.EAST, bv); cp.add(BorderLayout.SOUTH, bh); } public static void main(String[] args) { Console.run(new Box1(), 450, 200); } } ///:~ t
//: c13:Box1.java
// BoxLayouts vertical et horizontal.
// <applet code=Box1
// width=450 height=200> </applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;

public class Box1 extends JApplet {
  public void init() {
  Box bv = Box.createVerticalBox();
   for(int i = 0; i     bv.add(new JButton("" + i));
  Box bh = Box.createHorizontalBox();
   for(int i = 0; i     bh.add(new JButton("" + i));
  Container cp = getContentPane();
  cp.add(BorderLayout.EAST, bv);
  cp.add(BorderLayout.SOUTH, bh);
}
  public static void main(String[] args) {
  Console.run(new Box1(), 450, 200);
}
} ///:~
t t t
Once you have a Box, you pass it as a second argument when adding components to the content pane. t Une fois qu'on a obtenu un Box, on le passe en second argument quand on ajoute des composants au content pane.
t t t
Struts add space between components, measured in pixels. To use a strut, you simply add it in between the addition of the components that you want spaced apart: t Les struts ajoutent de l'espace entre les composants, mesuré en pixels. Pour utiliser un strut, on l'ajoute simplement entre les ajouts de composants que l'on veut séparer :
t t t
//: c13:Box2.java // Adding struts. // <applet code=Box2 // width=450 height=300> </applet> import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class Box2 extends JApplet { public void init() { Box bv = Box.createVerticalBox(); for(int i = 0; i < 5; i++) { bv.add(new JButton("" + i)); bv.add(Box.createVerticalStrut(i*10)); } Box bh = Box.createHorizontalBox(); for(int i = 0; i < 5; i++) { bh.add(new JButton("" + i)); bh.add(Box.createHorizontalStrut(i*10)); } Container cp = getContentPane(); cp.add(BorderLayout.EAST, bv); cp.add(BorderLayout.SOUTH, bh); } public static void main(String[] args) { Console.run(new Box2(), 450, 300); } } ///:~ t
//: c13:Box2.java
// Ajout de struts.
// <applet code=Box2
// width=450 height=300> </applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;

public class Box2 extends JApplet {
  public void init() {
  Box bv = Box.createVerticalBox();
   for(int i = 0; i     bv.add(new JButton("" + i));
    bv.add(Box.createVerticalStrut(i*10));
  }
  Box bh = Box.createHorizontalBox();
   for(int i = 0; i     bh.add(new JButton("" + i));
    bh.add(Box.createHorizontalStrut(i*10));
  }
  Container cp = getContentPane();
  cp.add(BorderLayout.EAST, bv);
  cp.add(BorderLayout.SOUTH, bh);
}
  public static void main(String[] args) {
  Console.run(new Box2(), 450, 300);
}
} ///:~
t t t
t t t
t t
\\\
///
t t t
t
     
Sommaire Le site de Bruce Eckel