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
The title for the border is taken from the name of the class, stripping off all the path information. The AbstractButton is initialized to a JButton that has the label “Failed” so if you ignore the exception message, you’ll still see the problem on screen. The getConstructor( ) method produces a Constructor object that takes the array of arguments of the types in the Class array passed to getConstructor( ). Then all you do is call newInstance( ), passing it an array of Object containing your actual arguments—in this case, just the String from the ids array. t Le titre de la bordure est construit à partir du nom de la classe, en enlevant tout ce qui concerne son chemin. L'AbstractButton est initialisé comme un JButton qui a le label "failed" de sorte que si on ignore un message d'exception le problème se verra à l'écran. La méthode getConstructor() fournit un objet Constructor qui prend un tableau d'arguments des types du tableau Class passé à getConstructor(). Ensuite il suffit d'appelernewInstance(), en lui passant un tableau d'Objects contenant les arguments, dans ce cas il s'agit des Strings du tableau ids.
t t t
This adds a little complexity to what is a simple process. To get “exclusive or” behavior with buttons, you create a button group and add each button for which you want that behavior to the group. When you run the program, you’ll see that all the buttons except JButton exhibit this “exclusive or” behavior. t Ceci ajoute un peu de complexité à ce qui est un processus simple. Pour obtenir un comportement de "OU exclusif" avec des boutons, on crée un groupe de boutons et on ajoute au groupe chaque bouton pour lequel on désire ce comportement. Lorsqu'on exécute le programme, on voit que tous les boutons, à l'exception de JButton, montrent ce comportement de "OU exclusif".
t t t

Icons

t

Icones

t t t
You can use an Icon inside a JLabel or anything that inherits from AbstractButton (including JButton, JCheckBox, JRadioButton, and the different kinds of JMenuItem). Using Icons with JLabels is quite straightforward (you’ll see an example later). The following example explores all the additional ways you can use Icons with buttons and their descendants. t On peut utiliser un Icon dans un JLabel ou tout ce qui hérite de AbstractButton (y compris JButton, JCheckBox, JRadioButton, et les différents types de JMenuItem). L'utilisation d'Icons avec des JLabels est assez directe (on verra un exemple plus tard). L'exemple suivant explore toutes les façons d'utiliser des Icons avec des boutons et leurs descendants.
t t t
You can use any gif files you want, but the ones used in this example are part of this book’s code distribution, available at www.BruceEckel.com. To open a file and bring in the image, simply create an ImageIcon and hand it the file name. From then on, you can use the resulting Icon in your program. t Vous pouvez utiliser les fichiers gif que vous voulez, mais ceux utilisés dans cet exemple font partie de la livraison du code de ce livre, disponible à www.BruceEckel.com. Pour ouvrir un fichier et utiliser l'image, il suffit de créer un ImageIcon et de lui fournir le nom du fichier. A partir de là on peut utiliser l'Icon obtenu dans le programme.
t t t
Note that path information is hard-coded into this example; you will need to change the path to correspond to the location of the image files. t Remarquez que l'information de chemin est codée en dur dans cet exemple; vous devrez changer ce chemin pour qu'il corresponde à l'emplacement des fichiers des images.
t t t
//: c13:Faces.java
// Icon behavior in Jbuttons.
// <applet code=Faces
//  width=250 height=100></applet>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.bruceeckel.swing.*;

public class Faces extends JApplet {
  // The following path information is necessary
  // to run via an applet directly from the disk:
  static String path =
    "C:/aaa-TIJ2-distribution/code/c13/";
  static Icon[] faces = {
    new ImageIcon(path + "face0.gif"),
    new ImageIcon(path + "face1.gif"),
    new ImageIcon(path + "face2.gif"),
    new ImageIcon(path + "face3.gif"),
    new ImageIcon(path + "face4.gif"),
  };
  JButton
    jb = new JButton("JButton", faces[3]),
    jb2 = new JButton("Disable");
  boolean mad = false;
  public void init() {
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    jb.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e){
        if(mad) {
          jb.setIcon(faces[3]);
          mad = false;
        } else {
          jb.setIcon(faces[0]);
          mad = true;
        }
        jb.setVerticalAlignment(JButton.TOP);
        jb.setHorizontalAlignment(JButton.LEFT);
      }
    });
    jb.setRolloverEnabled(true);
    jb.setRolloverIcon(faces[1]);
    jb.setPressedIcon(faces[2]);
    jb.setDisabledIcon(faces[4]);
    jb.setToolTipText("Yow!");
    cp.add(jb);
    jb2.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e){
        if(jb.isEnabled()) {
          jb.setEnabled(false);
          jb2.setText("Enable");
        } else {
          jb.setEnabled(true);
          jb2.setText("Disable");
        }
      }
    });
    cp.add(jb2);
  }
  public static void main(String[] args) {
    Console.run(new Faces(), 400, 200);
  }
} ///:~
t
//: c13:Faces.java
// Comportement des Icones dans des  Jbuttons.
// <applet code=Faces
//  width=250 height=100></applet>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.bruceeckel.swing.*;

public class Faces extends JApplet {
  // L'information de chemin suivante est nécessaire
  // pour l'exécution via une applet directement depuis le disque :
  static String path =
   "C:/aaa-TIJ2-distribution/code/c13/";
  static Icon[] faces = {
   new ImageIcon(path + "face0.gif"),
   new ImageIcon(path + "face1.gif"),
   new ImageIcon(path + "face2.gif"),
   new ImageIcon(path + "face3.gif"),
   new ImageIcon(path + "face4.gif"),
};
JButton
jb = new JButton("JButton", faces[3]),
jb2 = new JButton("Disable");
  boolean mad = false;
  public void init() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
jb.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e){
     if(mad) {
     jb.setIcon(faces[3]);
     mad = false;
   } else {
     jb.setIcon(faces[0]);
     mad = true;
   }
   jb.setVerticalAlignment(JButton.TOP);
   jb.setHorizontalAlignment(JButton.LEFT);
}
});
jb.setRolloverEnabled(true);
jb.setRolloverIcon(faces[1]);
jb.setPressedIcon(faces[2]);
jb.setDisabledIcon(faces[4]);
jb.setToolTipText("Yow!");
cp.add(jb);
jb2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e){
     if(jb.isEnabled()) {
     jb.setEnabled(false);
     jb2.setText("Enable");
   } else {
     jb.setEnabled(true);
     jb2.setText("Disable");
   }
}
});
cp.add(jb2);
}
  public static void main(String[] args) {
Console.run(new Faces(), 400, 200);
}
} ///:~
t t t
An Icon can be used in many constructors, but you can also use setIcon( ) to add or change an Icon. This example also shows how a JButton (or any AbstractButton) can set the various different sorts of icons that appear when things happen to that button: when it’s pressed, disabled, or “rolled over” (the mouse moves over it without clicking). You’ll see that this gives the button a nice animated feel. t Un Icon peut être utilisé dans de nombreux constructeurs, mais on peut aussi utiliser setIcon() pour ajouter ou changer un Icon. Cet exemple montre également comment un JButton (ou un quelconque AbstractButton) peut positionner les différentes sortes d'icones qui apparaissent lorsque des choses se passent sur ce bouton : lorsqu'il est enfoncé, invalidé, ou lorsqu'on roule par dessus [rolled over] (la souris passe au-dessus sans cliquer). On verra que ceci donne au bouton une sensation d'animation agréable.
t t t

Tool tips

t

Infobulles [Tooltips]

t t t
The previous example added a “tool tip” to the button. Almost all of the classes that you’ll be using to create your user interfaces are derived from JComponent, which contains a method called setToolTipText(String). So, for virtually anything you place on your form, all you need to do is say (for an object jc of any JComponent-derived class): t L'exemple précédent ajoutait un tool tip au bouton. La plupart des classes qu'on utilisera pour créer une interface utilisateur sont dérivées de JComponent, qui contient une méthode appelée setToolTipText(String). Donc pratiquement pour tout ce qu'on place sur un formulaire, il suffit de dire (pour un objet jc de toute classe dérivée de JComponent) :
t t t
jc.setToolTipText("My tip");
t
jc.setToolTipText("My tip");
t t t
and when the mouse stays over that
JComponent for a predetermined period of time, a tiny box containing your
text will pop up next to the mouse.
t et lorsque la souris reste au-dessus de ce JComponent pour un temps prédéterminé, une petite boîte contenant le texte va apparaître à côté de la souris.
t t t


Text fields


t

Champs de texte [Text Fields]

t t t
This example shows the extra behavior
that JTextFields are capable of:

t Cet exemple montre le comportement supplémentaire dont sont capables les JTextFields :
t t t
//: c13:TextFields.java
// Text fields and Java events.
// <applet code=TextFields width=375
// height=125></applet>
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import com.bruceeckel.swing.*;

public class TextFields extends JApplet {
  JButton
    b1 = new JButton("Get Text"),
    b2 = new JButton("Set Text");
  JTextField
    t1 = new JTextField(30),
    t2 = new JTextField(30),
    t3 = new JTextField(30);
  String s = new String();
  UpperCaseDocument
    ucd = new UpperCaseDocument();
  public void init() {
    t1.setDocument(ucd);
    ucd.addDocumentListener(new T1());
    b1.addActionListener(new B1());
    b2.addActionListener(new B2());
    DocumentListener dl = new T1();
    t1.addActionListener(new T1A());
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    cp.add(b1);
    cp.add(b2);
    cp.add(t1);
    cp.add(t2);
    cp.add(t3);
  }
  class T1 implements DocumentListener {
    public void changedUpdate(DocumentEvent e){}
    public void insertUpdate(DocumentEvent e){
      t2.setText(t1.getText());
      t3.setText("Text: "+ t1.getText());
    }
    public void removeUpdate(DocumentEvent e){
      t2.setText(t1.getText());
    }
  }
  class T1A implements ActionListener {
    private int count = 0;
    public void actionPerformed(ActionEvent e) {
      t3.setText("t1 Action Event " + count++);
    }
  }
  class B1 implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      if(t1.getSelectedText() == null)
        s = t1.getText();
      else
        s = t1.getSelectedText();
      t1.setEditable(true);
    }
  }
  class B2 implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      ucd.setUpperCase(false);
      t1.setText("Inserted by Button 2: " + s);
      ucd.setUpperCase(true);
      t1.setEditable(false);
    }
  }
  public static void main(String[] args) {
    Console.run(new TextFields(), 375, 125);
  }
}

class UpperCaseDocument extends PlainDocument {
  boolean upperCase = true;
  public void setUpperCase(boolean flag) {
    upperCase = flag;
  }
  public void insertString(int offset,
    String string, AttributeSet attributeSet)
    throws BadLocationException {
      if(upperCase)
        string = string.toUpperCase();
      super.insertString(offset,
        string, attributeSet);
  }
} ///:~
t
//: c13:TextFields.java
// Champs de texte et événements Java.
// <applet code=TextFields width=375
// height=125></applet>
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import com.bruceeckel.swing.*;

public class TextFields extends JApplet {
JButton
b1 = new JButton("Get Text"),
b2 = new JButton("Set Text");
JTextField
t1 = new JTextField(30),
t2 = new JTextField(30),
t3 = new JTextField(30);
String s = new String();
UpperCaseDocument
ucd = new UpperCaseDocument();
  public void init() {
t1.setDocument(ucd);
ucd.addDocumentListener(new T1());
b1.addActionListener(new B1());
b2.addActionListener(new B2());
DocumentListener dl = new T1();
t1.addActionListener(new T1A());
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b1);
cp.add(b2);
cp.add(t1);
cp.add(t2);
cp.add(t3);
}
  class T1 implements DocumentListener {
   public void changedUpdate(DocumentEvent e){}
   public void insertUpdate(DocumentEvent e){
t2.setText(t1.getText());
t3.setText("Text: "+ t1.getText());
}
   public void removeUpdate(DocumentEvent e){
t2.setText(t1.getText());
}
}
  class T1A implements ActionListener {
   private int count = 0;
   public void actionPerformed(ActionEvent e) {
t3.setText("t1 Action Event " + count++);
}
}
  class B1 implements ActionListener {
   public void actionPerformed(ActionEvent e) {
    if(t1.getSelectedText() == null)
   s = t1.getText();
    else
   s = t1.getSelectedText();
t1.setEditable(true);
}
}
  class B2 implements ActionListener {
   public void actionPerformed(ActionEvent e) {
ucd.setUpperCase(false);
t1.setText("Inserted by Button 2: " + s);
ucd.setUpperCase(true);
t1.setEditable(false);
}
}
  public static void main(String[] args) {
Console.run(new TextFields(), 375, 125);
}
}

class UpperCaseDocument extends PlainDocument {
  boolean upperCase = true;
  public void setUpperCase(boolean flag) {
upperCase = flag;
}
  public void insertString(int offset,
String string, AttributeSet attributeSet)
   throws BadLocationException {
    if(upperCase)
   string = string.toUpperCase();
    super.insertString(offset,
   string, attributeSet);
}
} ///:~
t t t
The JTextField t3 is included as a place to report when the action listener for the JTextField t1 is fired. You’ll see that the action listener for a JTextField is fired only when you press the “enter” key. t Le JTextField t3 est inclus pour servir d'emplacement pour signaler lorsque l'action listener du JTextField t1 est lancé.On verra que l'action listener d'un JTextField n'est lancé que lorsqu'on appuie sur la touche enter.
t t t
The JTextField t1 has several listeners attached to it. The T1 listener is a DocumentListener that responds to any change in the “document” (the contents of the JTextField, in this case). It automatically copies all text from t1 into t2. In addition, t1’s document is set to a derived class of PlainDocument, called UpperCaseDocument, which forces all characters to uppercase. It automatically detects backspaces and performs the deletion, adjusting the caret and handling everything as you would expect. t Le JTextField t1 a plusieurs listeners attachés. le listener T1 est un Document Listener qui répond à tout changement dans le document (le contenu du JTextField, dans ce cas). Il copie automatiquement tout le texte de t1 dans t2. De plus, le document t1 est positionné à une classe dérivée de PlainDocument, appelée UpperCaseDocument, qui force tous les caractères en majuscules. Il détecte automatiquement les retours en arrière [backspaces]et effectue l'effacement, tout en ajustant le curseur et gérant tout de la manière attendue.
t t t

Borders

t

Bordures

t t t
JComponent contains a method called setBorder( ), which allows you to place various interesting borders on any visible component. The following example demonstrates a number of the different borders that are available, using a method called showBorder( ) that creates a JPanel and puts on the border in each case. Also, it uses RTTI to find the name of the border that you’re using (stripping off all the path information), then puts that name in a JLabel in the middle of the panel: t JComponent possède une méthode appelée setBorder(), qui permet de placer différentes bordures intéressantes sur tout composant visible. L'exemple suivant montre certaines des bordures existantes, en utilisant la méthode showBorder() qui crée un JPanel et lui attache une bordure à chaque fois. Il utilise aussi RTTI pour trouver le nom de la bordure qu'on utilise (en enlevant l'information du chemin), et met ensuite le nom dans un JLabel au milieu du panneau :
t t t
//: c13:Borders.java
// Different Swing borders.
// <applet code=Borders
//  width=500 height=300></applet>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import com.bruceeckel.swing.*;

public class Borders extends JApplet {
  static JPanel showBorder(Border b) {
    JPanel jp = new JPanel();
    jp.setLayout(new BorderLayout());
    String nm = b.getClass().toString();
    nm = nm.substring(nm.lastIndexOf('.') + 1);
    jp.add(new JLabel(nm, JLabel.CENTER),
      BorderLayout.CENTER);
    jp.setBorder(b);
    return jp;
  }
  public void init() {
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    cp.setLayout(new GridLayout(2,4));
    cp.add(showBorder(new TitledBorder("Title")));
    cp.add(showBorder(new EtchedBorder()));
    cp.add(showBorder(new LineBorder(Color.blue)));
    cp.add(showBorder(
      new MatteBorder(5,5,30,30,Color.green)));
    cp.add(showBorder(
      new BevelBorder(BevelBorder.RAISED)));
    cp.add(showBorder(
      new SoftBevelBorder(BevelBorder.LOWERED)));
    cp.add(showBorder(new CompoundBorder(
      new EtchedBorder(),
      new LineBorder(Color.red))));
  }
  public static void main(String[] args) {
    Console.run(new Borders(), 500, 300);
  }
} ///:~
t
//: c13:Borders.java
// Diverses bordures Swing.
// <applet code=Borders
//  width=500 height=300></applet>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import com.bruceeckel.swing.*;

public class Borders extends JApplet {
  static JPanel showBorder(Border b) {
    JPanel jp = new JPanel();
    jp.setLayout(new BorderLayout());
    String nm = b.getClass().toString();
    nm = nm.substring(nm.lastIndexOf('.') + 1);
    jp.add(new JLabel(nm, JLabel.CENTER),
      BorderLayout.CENTER);
    jp.setBorder(b);
    return jp;
  }
  public void init() {
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    cp.setLayout(new GridLayout(2,4));
    cp.add(showBorder(new TitledBorder("Title")));
    cp.add(showBorder(new EtchedBorder()));
    cp.add(showBorder(new LineBorder(Color.blue)));
    cp.add(showBorder(
      new MatteBorder(5,5,30,30,Color.green)));
    cp.add(showBorder(
      new BevelBorder(BevelBorder.RAISED)));
    cp.add(showBorder(
      new SoftBevelBorder(BevelBorder.LOWERED)));
    cp.add(showBorder(new CompoundBorder(
      new EtchedBorder(),
      new LineBorder(Color.red))));
  }
  public static void main(String[] args) {
    Console.run(new Borders(), 500, 300);
  }
} ///:~
t t t
You can also create your own borders and put them inside buttons, labels, etc.—anything derived from JComponent. t On peut également créer ses propres bordures et les placer dans des boutons, labels, et cetera, tout ce qui est dérivé de JComponent.
t t t

JScrollPanes

t

JScrollPanes

t t t
Most of the time you’ll just want to let a JScrollPane do it’s job, but you can also control which scroll bars are allowed—vertical, horizontal, both, or neither: t La plupart du temps on laissera le JScrollPane tel quel, mais on peut aussi contrôler quelles barres de défilement sont autorisées, verticales, horizontales, les deux ou ni l'une ni l'autre :
t t t
//: c13:JScrollPanes.java
// Controlling the scrollbars in a JScrollPane.
// <applet code=JScrollPanes width=300 height=725>
// </applet>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import com.bruceeckel.swing.*;

public class JScrollPanes extends JApplet {
  JButton
    b1 = new JButton("Text Area 1"),
    b2 = new JButton("Text Area 2"),
    b3 = new JButton("Replace Text"),
    b4 = new JButton("Insert Text");
  JTextArea
    t1 = new JTextArea("t1", 1, 20),
    t2 = new JTextArea("t2", 4, 20),
    t3 = new JTextArea("t3", 1, 20),
    t4 = new JTextArea("t4", 10, 10),
    t5 = new JTextArea("t5", 4, 20),
    t6 = new JTextArea("t6", 10, 10);
  JScrollPane
    sp3 = new JScrollPane(t3,
      JScrollPane.VERTICAL_SCROLLBAR_NEVER,
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),
    sp4 = new JScrollPane(t4,
      JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),
    sp5 = new JScrollPane(t5,
      JScrollPane.VERTICAL_SCROLLBAR_NEVER,
      JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS),
    sp6 = new JScrollPane(t6,
      JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
      JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
  class B1L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      t5.append(t1.getText() + "\n");
    }
  }
  class B2L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      t2.setText("Inserted by Button 2");
      t2.append(": " + t1.getText());
      t5.append(t2.getText() + "\n");
    }
  }
  class B3L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      String s = " Replacement ";
      t2.replaceRange(s, 3, 3 + s.length());
    }
  }
  class B4L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      t2.insert(" Inserted ", 10);
    }
  }
  public void init() {
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    // Create Borders for components:
    Border brd = BorderFactory.createMatteBorder(
      1, 1, 1, 1, Color.black);
    t1.setBorder(brd);
    t2.setBorder(brd);
    sp3.setBorder(brd);
    sp4.setBorder(brd);
    sp5.setBorder(brd);
    sp6.setBorder(brd);
    // Initialize listeners and add components:
    b1.addActionListener(new B1L());
    cp.add(b1);
    cp.add(t1);
    b2.addActionListener(new B2L());
    cp.add(b2);
    cp.add(t2);
    b3.addActionListener(new B3L());
    cp.add(b3);
    b4.addActionListener(new B4L());
    cp.add(b4);
    cp.add(sp3);
    cp.add(sp4);
    cp.add(sp5);
    cp.add(sp6);
  }
  public static void main(String[] args) {
    Console.run(new JScrollPanes(), 300, 725);
  }
} ///:~
t
//: c13:JScrollPanes.java
// Contrôle des scrollbars d'un JScrollPane.
// <applet code=JScrollPanes width=300 height=725>
// </applet>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import com.bruceeckel.swing.*;

public class JScrollPanes extends JApplet {
  JButton
    b1 = new JButton("Text Area 1"),
    b2 = new JButton("Text Area 2"),
    b3 = new JButton("Replace Text"),
    b4 = new JButton("Insert Text");
  JTextArea
    t1 = new JTextArea("t1", 1, 20),
    t2 = new JTextArea("t2", 4, 20),
    t3 = new JTextArea("t3", 1, 20),
    t4 = new JTextArea("t4", 10, 10),
    t5 = new JTextArea("t5", 4, 20),
    t6 = new JTextArea("t6", 10, 10);
  JScrollPane
    sp3 = new JScrollPane(t3,
      JScrollPane.VERTICAL_SCROLLBAR_NEVER,
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),
    sp4 = new JScrollPane(t4,
      JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
      JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),
    sp5 = new JScrollPane(t5,
      JScrollPane.VERTICAL_SCROLLBAR_NEVER,
      JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS),
    sp6 = new JScrollPane(t6,
      JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
      JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
  class B1L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      t5.append(t1.getText() + "\n");
    }
  }
  class B2L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      t2.setText("Inserted by Button 2");
      t2.append(": " + t1.getText());
      t5.append(t2.getText() + "\n");
    }
  }
  class B3L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      String s = " Replacement ";
      t2.replaceRange(s, 3, 3 + s.length());
    }
  }
  class B4L implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      t2.insert(" Inserted ", 10);
    }
  }
  public void init() {
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    // Création de Borders pour les composants:
    Border brd = BorderFactory.createMatteBorder(
      1, 1, 1, 1, Color.black);
    t1.setBorder(brd);
    t2.setBorder(brd);
    sp3.setBorder(brd);
    sp4.setBorder(brd);
    sp5.setBorder(brd);
    sp6.setBorder(brd);
    // Initialisation des listeners et ajout des composants:
    b1.addActionListener(new B1L());
    cp.add(b1);
    cp.add(t1);
    b2.addActionListener(new B2L());
    cp.add(b2);
    cp.add(t2);
    b3.addActionListener(new B3L());
    cp.add(b3);
    b4.addActionListener(new B4L());
    cp.add(b4);
    cp.add(sp3);
    cp.add(sp4);
    cp.add(sp5);
    cp.add(sp6);
  }
  public static void main(String[] args) {
    Console.run(new JScrollPanes(), 300, 725);
  }
} ///:~
t t t
Using different arguments in the JScrollPane constructor controls the scrollbars that are available. This example also dresses things up a bit using borders. t L'utilisation des différents arguments du constructeur de JScrollPane contrôle la présence des scrollbars. Cet exemple est également un peu "habillé" à l'aide de bordures.
t t t

A mini-editor

t

Un mini-éditeur

t t t
The JTextPane control provides a great deal of support for editing, without much effort. The following example makes very simple use of this, ignoring the bulk of the functionality of the class: t Le contrôle JTextPane fournit un support important pour l'édition de texte, sans grand effort. L'exemple suivant en fait une utilisation très simple, en ignorant le plus gros des fonctionnalités de la classe :
t t t
//: c13:TextPane.java
// The JTextPane control is a little editor.
// <applet code=TextPane width=475 height=425>
// </applet>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.bruceeckel.swing.*;
import com.bruceeckel.util.*;

public class TextPane extends JApplet {
  JButton b = new JButton("Add Text");
  JTextPane tp = new JTextPane();
  static Generator sg =
    new Arrays2.RandStringGenerator(7);  
  public void init() {
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e){
        for(int i = 1; i < 10; i++)
          tp.setText(tp.getText() +
            sg.next() + "\n");
      }
    });
    Container cp = getContentPane();
    cp.add(new JScrollPane(tp));
    cp.add(BorderLayout.SOUTH, b);
  }
  public static void main(String[] args) {
    Console.run(new TextPane(), 475, 425);
  }
} ///:~
t
//: c13:TextPane.java
// Le contrôle JTextPane est un petit éditeur de texte.
// <applet code=TextPane width=475 height=425>
// </applet>
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import com.bruceeckel.swing.*;
import com.bruceeckel.util.*;

public class TextPane extends JApplet {
  JButton b = new JButton("Add Text");
  JTextPane tp = new JTextPane();
  static Generator sg =
    new Arrays2.RandStringGenerator(7);  
  public void init() {
    b.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e){
        for(int i = 1; i < 10; i++)
          tp.setText(tp.getText() +
            sg.next() + "\n");
      }
    });
    Container cp = getContentPane();
    cp.add(new JScrollPane(tp));
    cp.add(BorderLayout.SOUTH, b);
  }
  public static void main(String[] args) {
    Console.run(new TextPane(), 475, 425);
  }
} ///:~
t t t
The button just adds randomly generated text. The intent of the JTextPane is to allow text to be edited in place, so you will see that there is no append( ) method. In this case (admittedly, a poor use of the capabilities of JTextPane), the text must be captured, modified, and placed back into the pane using setText( ). t Le bouton ajoute simplement au hasard du texte généré. Le but du JTextPane est de permettre la modification de texte sur place, de sorte qu'on ne trouvera pas de méthode append(). Dans ce cas-ci (il est admis qu'il s'agit d'un piètre usage des capacités de JTextPane), le texte doit être saisi, modifié, et replacé dans le panneau en utilisant setText().
t t t
t t t
t t
\\\
///
t t t
t
     
Sommaire Le site de Bruce Eckel