1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| package source;
import java.awt.Toolkit;
import java.text.DecimalFormat;
import javax.swing.text.*;
/****
* Classe DDocumentNumber : permet de personnaliser la gestion du "model" des composants Texte
* proposee dans l'api de swing
*
****/
public class FiltreFlottant extends PlainDocument
{
private int longueur;
private double min,max;
public FiltreFlottant(int taille,Double min,Double max)
{
super ();
this.longueur = taille; // represente le nombre de digit maximum
this.min = min;
this.max = max; // represente la valeur limite a ne pas depasser par le champ a saisir
System.out.println(longueur);
System.out.println(this.min);
System.out.println(this.max);
}
/**
* Redefini la methode de la classe PlainDocument permettant ainsi d'autoriser
* uniquement les caracteres desires
*/
public void insertString (int offs, String str, AttributeSet a) throws BadLocationException
{
StringBuffer sb = new StringBuffer ();
char car;
if(this.getLength()<longueur)
{
for (int i=0; i<str.length(); i++)
{
car = str.charAt(i);
if(car==',')
car='.';
if (Character.isDigit (car)||(car=='.'))
{
sb.append(car);
}
else
{
Toolkit.getDefaultToolkit().beep();
System.out.println("la caractere saisie n'est pas un chiffre");
}
}
//ajout du digit a la position off
super.insertString(offs, sb.toString(), a);
//on test si le nombre saisie depasse la valeur maximale
//si oui on annule l'ajout qui vient d'etre fait
try{
if ((Double.parseDouble(this.getText(0,this.getLength()))<min)||(Double.parseDouble(this.getText(0,this.getLength()))>max))
{
super.remove(offs, sb.length());
Toolkit.getDefaultToolkit().beep();
}
}
catch(Exception e)
{
System.out.println("erreur de saisie");
super.remove(offs, sb.length());
Toolkit.getDefaultToolkit().beep();
}
}
else
{
Toolkit.getDefaultToolkit().beep();
System.out.println("taille depasser");
}
}
} |
Partager