API java : Formattable


java.util
Interface Formattable


public interface Formattable

The Formattable interface must be implemented by any class that needs to perform custom formatting using the 's' conversion specifier of Formatter. This interface allows basic control for formatting arbitrary objects. For example, the following class prints out different representations of a stock's name depending on the flags and length constraints:

  1. import java.nio.CharBuffer;
  2. import java.util.Formatter;
  3. import java.util.Formattable;
  4. import java.util.Locale;
  5. import static java.util.FormattableFlags.*;
  6.  
  7. ...
  8.  
  9. public class StockName implements Formattable {
  10. private String symbol, companyName, frenchCompanyName;
  11. public StockName(String symbol, String companyName,
  12. String frenchCompanyName) {
  13. ...
  14. }
  15.  
  16. ...
  17.  
  18. public void formatTo(Formatter fmt, int f, int width, int precision) {
  19.  
  20. // decide form of name
  21. String name = companyName;
  22. if (fmt.locale().equals(Locale.FRANCE))
  23. name = frenchCompanyName;
  24. boolean alternate = (f & ALTERNATE) == ALTERNATE;
  25. boolean usesymbol = alternate || (precision != -1 && precision < 10);
  26. String out = (usesymbol ? symbol : name);
  27.  
  28. // apply precision
  29. if (precision == -1 || out.length() < precision) {
  30. // write it all
  31. sb.append(out);
  32. } else {
  33. sb.append(out.substring(0, precision - 1)).append('*');
  34. }
  35.  
  36. // apply width and justification
  37. int len = sb.length();
  38. if (len < width)
  39. for (int i = 0; i < width - len; i++)
  40. if ((f & LEFT_JUSTIFY) == LEFT_JUSTIFY)
  41. sb.append(' ');
  42. else
  43. sb.insert(0, ' ');
  44.  
  45. fmt.format(sb.toString());
  46. }
  47.  
  48. public String toString() {
  49. return String.format("%s - %s", symbol, companyName);
  50. }
  51. }

When used in conjunction with the Formatter, the above class produces the following output for various format strings.

  1. Formatter fmt = new Formatter();
  2. StockName sn = new StockName("HUGE", "Huge Fruit, Inc.",
  3. "Fruit Titanesque, Inc.");
  4. fmt.format("%s", sn); // -> "Huge Fruit, Inc."
  5. fmt.format("%s", sn.toString()); // -> "HUGE - Huge Fruit, Inc."
  6. fmt.format("%#s", sn); // -> "HUGE"
  7. fmt.format("%-10.8s", sn); // -> "HUGE "
  8. fmt.format("%.12s", sn); // -> "Huge Fruit,*"
  9. fmt.format(Locale.FRANCE, "%25s", sn); // -> " Fruit Titanesque, Inc."

Formattables are not necessarily safe for multithreaded access. Thread safety is optional and may be enforced by classes that extend and implement this interface.

Unless otherwise specified, passing a null argument to any method in this interface will cause a NullPointerException to be thrown.

Since:
1.5

Method Summary
 void formatTo(Formatter formatter, int flags, int width, int precision)
          Formats the object using the provided formatter.
 

Method Detail

formatTo

void formatTo(Formatter formatter,
              int flags,
              int width,
              int precision)
Formats the object using the provided formatter.

Parameters:
formatter - The formatter. Implementing classes may call formatter.out() or formatter.locale() to obtain the Appendable or Locale used by this formatter respectively.
flags - The flags modify the output format. The value is interpreted as a bitmask. Any combination of the following flags may be set: FormattableFlags.LEFT_JUSTIFY, FormattableFlags.UPPERCASE, and FormattableFlags.ALTERNATE. If no flags are set, the default formatting of the implementing class will apply.
width - The minimum number of characters to be written to the output. If the length of the converted value is less than the width then the output will be padded by '  ' until the total number of characters equals width. The padding is at the beginning by default. If the FormattableFlags.LEFT_JUSTIFY flag is set then the padding will be at the end. If width is -1 then there is no minimum.
precision - The maximum number of characters to be written to the output. The precision is applied before the width, thus the output will be truncated to precision characters even if the width is greater than the precision. If precision is -1 then there is no explicit limit on the number of characters.
Throws:
IllegalFormatException - If any of the parameters are invalid. For specification of all possible formatting errors, see the Details section of the formatter class specification.

Ces informations proviennent du site de http://java.sun.com

Remarques

Contenu

Le contenu de cette page provient du site de Sun, et est généré depuis un cache sur l'infobrol après certains traitements automatisés. La présentation peut donc différer du document original, mais le contenu aussi. Vous pouvez utiliser ce bouton pour afficher la page originale du site de Sun :

Quels sont les motivations de cette démarche?

Maintenir les pages en cache sur différents sites peut offrir plus de disponibilité.

Chaque page est indexée dans la base de donnée, ce qui permet de retrouver facilement les informations, au moyen des sommaires, du moteur de recherche interne, etc.

Des facilités sont mises en place pour que les membres de l'infobrol puissent effectuer des traductions en français des différents documents. Ceci devrait permettre aux débutants en programmation Java de consulter les API en français s'ils maîtrisent moins bien la langue de Shakespeare. Dans le cas où une traduction a été soumise, elle est disponible au moyen d'un lien en bas de page. Si la traduction a été validée, la page s'affiche par défaut en français, et un lien en bas de page permet d'atteindre la version en anglais.

Le code sur l'infobrol est automatiquement coloré selon la syntaxe, et les différents mots clés sont transformés en liens pour accéder rapidement aux informations.

Vous avez la possibilité de partager vos expériences en proposant vos propres extraits de code en utilisant le bouton "ajouter un commentaire" en bas de page. Si vous visitez simplement l'infobrol, vous avez déjà accès à cette fonction, mais si vous étes membre du brol, vous pouvez en plus utiliser des boutons supplémentaires de mise en forme, dont la coloration automatique de vos extraits de codes.

Réseaux sociaux

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher les interactions avec les réseaux sociaux sur ces pages.

 

Nuage de mots clés

6 mots clés dont 0 définis manuellement (plus d'information...).

Avertissement

Cette page ne possède pas encore de mots clés manuels, ceci est donc un exemple automatique (les niveaux de pertinence sont fictifs, mais les liens sont valables). Pour tester le nuage avec une page qui contient des mots définis manuellement, vous pouvez cliquer ici.

Vous pouvez modifier vos préférences dans votre profil pour ne plus afficher le nuage de mots clés.

 

Astuce pour imprimer les couleurs des cellules de tableaux : http://www.gaudry.be/ast-rf-450.html
Aucun commentaire pour cette page

© Ce document issu de l′infobrol est enregistré sous le certificat Cyber PrInterDeposit Digital Numbertection. Enregistrement IDDN n° 5329-1256
Document créé le 29/08/06 21:10, dernière modification le Vendredi 17 Juin 2011, 12:12
Source du document imprimé : http://www.gaudry.be/java-api-rf-java/util/Formattable.html Document affiché 1 fois ce mois de Juin.
St.Gaudry©07.01.02
Outils (masquer)
||
Recherche (afficher)
Recherche :

Utilisateur (masquer)
Navigation (masquer)
Apparence (afficher)
Stats (afficher)
15832 documents
452 astuces.
549 niouzes.
3099 definitions.
447 membres.
8115 messages.

Document genere en :
0,78 seconde

Mises à jour :
Mises à jour du site
Citation (masquer)
Sangoku a un poster de Chuck Norris dans sa chambre.

Anonyme [Chuck Norris fact]
 
l'infobrol
Nous sommes le Vendredi 01 Juin 2012, 19:50, toutes les heures sont au format GMT+1.00 Heure, heure d'été (+1)