Dans cette section, nous allons voir comment écrire (ou plus exactement dessiner du texte) sur une fenêtre graphique en choisissant les fontes, les couleurs etc. Comme nous l'avons déjà vu, la classe Graphics fournit les les méthodes pour dessiner du texte avec la méthode drawString. Les classes java.awt.Font et java.awt.FontMetrics met à la disposition du programmeur un ensemble d'outils pour la gestion des caractères. Rappelons que la classe Graphics maintient ce que nous avons appelé contexte graphique i.e. les informations sur les opérations graphiques: couleurs, fontes, emplacement et dimension du rectangle de clipping . Le contexte graphique définit également la destination des opérations graphiques.
La classe Graphics définit trois méthodes pour dessiner du texte dans une fenêtre graphique.
Dans la méthode drawString(String str, int x, int y), str est la chaîne de caractères que l'on veut dessiner et (x, y) les coordonnées de la localisation du début du texte.
void drawString(String str, int x, int y) void drawChars(char [] data, int offset, int length, int x, int y) void drawBytes(byte [] data, int offset, int length, int x, int y)
Dans la méthode void drawChars(char [] data, int offset, int length, int x, int y), data est un tableau de caractères, offset d'indice du début du texte à dessiner, length le nombre de carcatère à dessiner et (x, y) les coordonnées de la localisation du début du texte.
public void paint(Graphics g) { g.drawString("coucou !", 25, 25); }
public void paint(Graphics g) { char [] texte = {'c', 'o', 'u', 'c', 'o', 'u', ' ', '!'}; g.drawString(texte, 0, 3, 25, 25); g.drawString(texte, 3, 5, 25, 50); }
Dans la méthode void drawBytes(byte [] data, int offset, int length, int x, int y), data est un tableau d'octets, offset d'indice du début du texte à dessiner, length le nombre de carcatère à dessiner et (x, y) les coordonnées de la localisation du début du texte.
public void paint(Graphics g) { byte[] texte = {'c', 'o', 'u', 'c', 'o', 'u', ' ', '!'}; g.drawByte(texte, 0, 3, 25, 25); g.drawByte(texte, 3, 5, 25, 50); }
La classe java.awt.Font permet de définir et manipuler les fontes: famille, style, taille, etc. Pour écrire avec une fonte particulière, il faut associer la fonte choisie avec l'objet Graphics :
Font f = new Font("Dialog", Font.PLAIN, 12); g.setFont(f);
Les différentes familles de fontes sont Dialog, Helvetica, TimesRoman, Courier, Symbol, etc.
Le style d'une fonte est donnée par l'une des valeurs suivantes: PLAIN, BOLD et ITALIC.
A TERMINER
L'écriture d'un texte dans une fenêtre graphique n'est qu'un cas particulier de dessin. Un texte (comme une quelconque dessin) peut être positionné n'importe où dans la zone dédiée. La position du texte dans une fenêtre ne peut être le fait du hasard; particulièrement lorsque le texte tient sur plusieurs lignes. Pour pouvoir positionner correctement du texte, il nous faut connaître les caractéristiques graphique de la fonte utilisée:
Lignes d'écriture
Nous avons dit que les arguments (x, y) des méthodes drawString drawChars drawBytes définissent la position du début du texte. On peut, à présent, être plus précis: les arguments (x, y) de ces méthodes définissent la position du baseline du début du texte.
public abstract class FontMetrics extends Object implements Serializable { protected Font font protected FontMetrics(Font font) public Font getFont() public int getLeading() public int getAscent() public int getDescent() public int getHeight() public int getMaxAscent() public int getMaxDescent() public int getMaxDecent() public int getMaxAdvance() public int charWidth(int ch) public int charWidth(char ch) public int stringWidth(String str) public int charsWidth(char[] data, int off, int len) public int bytesWidth(byte[] data, int off, int len) public int[] getWidths() public String toString() }
La classe java.awt.FontMetrics fournit les caractéristiques de la fonte utilisée. Par exemple, si l'on veut encadrer un texte, on pourra utiliser les méthodes getAscent, stringWidth et getHeight:
import java.awt.*; public class Fontes extends java.applet.Applet { String str = "Coucou !!!"; public void paint(java.awt.Graphics g) { g.setFont(new Font("Dialog", Font.BOLD, 32)); FontMetrics fm = g.getFontMetrics(g.getFont()); g.drawString(str, 20+3, 20+fm.getAscent()+3); g.drawRect(20, 20, fm.stringWidth(str) + 3, fm.getHeight() + 3); } }
Il existe plusieurs manières de coder les couleurs:
De plus, l'information sur une couleur peut être donnée en spécifiant la couleur de chaque pixel
Par défaut, AWT utilise le modèle de couleurs (color model ) nommée ARGB où A désigne la transparence (Alpha ) et RGB désigne le système évoqué précédemment.
Dans ce modèle, chaque est représenté par un entier de 4 octets; chaque octet désignant la quantité d'un des quatre composants.

Codage ARGB
public class Color extends Object implements Paint, Serializable { public static final Color white public static final Color lightGray public static final Color gray public static final Color darkGray public static final Color black public static final Color red public static final Color pink public static final Color orange public static final Color yellow public static final Color green public static final Color magenta public static final Color cyan public static final Color blue public Color(int r, int g, int b) public Color(int r, int g, int b, int a) public Color(int rgb) public Color(int rgba, boolean hasalpha) public Color(float r, float g, float b) public Color(float r, float g, float b, float a) public Color(ColorSpace cspace, float[] components, float alpha) public int getRed() public int getGreen() public int getBlue() public int getAlpha() public int getRGB() public int getRGBA() public Color brighter() public Color darker() public int hashCode() public boolean equals(Object obj) public String toString() public static Color decode(String nm) throws NumberFormatException public static Color getColor(String nm) public static Color getColor(String nm, Color v) public static Color getColor(String nm, int v) public static int HSBtoRGB(float hue, float saturation, float brightness) public static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals) public static Color getHSBColor(float h, float s, float b) public float[] getRGBComponents(float[] compArray) public float[] getRGBColorComponents(float[] compArray) public float[] getComponents(float[] compArray) public float[] getColorComponents(float[] compArray) public float[] getComponents(ColorSpace cspace, float[] compArray) public float[] getColorComponents(ColorSpace cspace, float[] compArray) public ColorSpace getColorSpace() public PaintContext createContext(ColorModel cm, Rectangle r, Rectangle2D r2d, AffineTransform xform) public int getTransparency() }
import java.awt.*; import java.awt.event.*; import java.applet.*; public class Couleurs extends Applet implements AdjustmentListener { int r = 255; int g = 255; int b = 255; Scrollbar sbRed = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 1, 257); Scrollbar sbGreen = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 1, 257); Scrollbar sbBlue = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 1, 257); Scrollbar sbH = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 1, 1002); Scrollbar sbS = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 1, 1002); Scrollbar sbB = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 1, 1002); TextField status = new TextField(); float[] hsb; public void init() { sbRed.addAdjustmentListener(this); sbGreen.addAdjustmentListener(this); sbBlue.addAdjustmentListener(this); sbH.addAdjustmentListener(this); sbS.addAdjustmentListener(this); sbB.addAdjustmentListener(this); add(makeScrollbars("R", sbRed, "G", sbGreen, "B", sbBlue), BorderLayout.WEST); add(makeScrollbars("H", sbH, "S", sbS, "B", sbB), BorderLayout.EAST); status.setEditable(false); add(status, BorderLayout.SOUTH); setSize(300, 300); show(); setBackground(adjustHSBScrollbars()); adjustRGBScrollbars(); } Panel makeScrollbars(String l1, Scrollbar sb1, String l2, Scrollbar sb2, String l3, Scrollbar sb3) { double[] rowWeights = {0.0, 1.0}; GridBagLayout gbl = new GridBagLayout(); Panel p = new Panel(gbl); gbl.rowWeights = rowWeights; p.setLayout(gbl); add(p, gbl, new Label(l1, Label.CENTER), 0, 0, GridBagConstraints.NONE); add(p, gbl, sb1, 0, 1, GridBagConstraints.VERTICAL); add(p, gbl, new Label(l2, Label.CENTER), 1, 0, GridBagConstraints.NONE); add(p, gbl, sb2, 1, 1, GridBagConstraints.VERTICAL); add(p, gbl, new Label(l3, Label.CENTER), 2, 0, GridBagConstraints.NONE); add(p, gbl, sb3, 2, 1, GridBagConstraints.VERTICAL); return p; } void add(Panel p, GridBagLayout gbl, Component comp, int x, int y, int fill) { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = x; gbc.gridy = y; gbc.fill = fill; gbl.setConstraints(comp, gbc); p.add(comp); } public void adjustmentValueChanged(AdjustmentEvent evt) { Color c = getBackground(); Object src = evt.getSource(); // Value from scrollbar is one greater than actual RGB or HSB value if (src == sbRed) { r = 255-(sbRed.getValue()-1); c = adjustHSBScrollbars(); } else if (src == sbGreen) { g = 255-(sbGreen.getValue()-1); c = adjustHSBScrollbars(); } else if (src == sbBlue) { b = 255-(sbBlue.getValue()-1); c = adjustHSBScrollbars(); } else if (src == sbH) { hsb[0] = (1000-(sbH.getValue()-1)) / 1000.0f; c = adjustRGBScrollbars(); } else if (src == sbS) { hsb[1] = (1000-(sbS.getValue()-1)) / 1000.0f; c = adjustRGBScrollbars(); } else if (src == sbB) { hsb[2] = (1000-(sbB.getValue()-1)) / 1000.0f; c = adjustRGBScrollbars(); } setBackground(c); repaint(); status.setText("RGB("+r+","+g+","+b+" / "+ "#"+Integer.toString(c.getRGB()&0xffffff, 16)+")"+ " HSB("+hsb[0]+","+hsb[1]+","+hsb[2]+")"); } Color adjustHSBScrollbars() { hsb = Color.RGBtoHSB(r, g, b, null); // need to offset values by 1 to account for 'visible' part // of scrollbar sbH.setValue(1001-(int)(hsb[0] * 1000)); sbS.setValue(1001-(int)(hsb[1] * 1000)); sbB.setValue(1001-(int)(hsb[2] * 1000)); return new Color(r, g, b); } Color adjustRGBScrollbars() { Color c = Color.getHSBColor(hsb[0], hsb[1], hsb[2]); // An alternate way of converting the HSB values to RGB: // Color c = new Color(Color.HSBtoRGB(hsb[0], hsb[1], hsb[2])); // need to offset values by 1 to account for 'visible' part // of scrollbar sbRed.setValue(256-(r = c.getRed())); sbGreen.setValue(256-(g = c.getGreen())); sbBlue.setValue(256-(b = c.getBlue())); return c; } }
A TERMINER