JTextField un nombre

Résolu
calla25 Messages postés 85 Date d'inscription lundi 26 janvier 2004 Statut Membre Dernière intervention 25 octobre 2007 - 30 nov. 2005 à 09:33
Twinuts Messages postés 5375 Date d'inscription dimanche 4 mai 2003 Statut Modérateur Dernière intervention 14 juin 2023 - 2 déc. 2005 à 14:29
Bonjour,
je suit débutante en java
et
je voudrais savoir comment on vérifie si un JTextField est un nombre
merci d'avance

3 réponses

cs_ducheseb Messages postés 344 Date d'inscription mardi 18 mai 2004 Statut Membre Dernière intervention 23 juin 2006 9
30 nov. 2005 à 10:47
Si tu veux uniquement saisir un nombre, tu peux choisir d'utiliser un JSpinner ou un JFormattedTextField (JFormattedTextField tft1 = new JFormattedTextField(NumberFormat.getIntegerInstance());)

Sinon, tu peux vérifier le contenu de ton JTextField:
String tmp = jtf.getText();
try{
Integer.parseInt(tmp);
}catch(NumberFormatException nfe){
System.out.println("Ce n'est pas un nombre");
jtf.setText("");
}

"A game is a series of interesting choices." Sid Meier
3
calla25 Messages postés 85 Date d'inscription lundi 26 janvier 2004 Statut Membre Dernière intervention 25 octobre 2007
30 nov. 2005 à 12:36
Merci beaucoup,
avec la solution du try ca marche trés trés bien
merci encore
0
Twinuts Messages postés 5375 Date d'inscription dimanche 4 mai 2003 Statut Modérateur Dernière intervention 14 juin 2023 111
2 déc. 2005 à 14:29
Salut,



sinon tu peux toujours créer un modèle générique pour les JTextField et
la l'utilisateur ne pourra pas saisir autre chose qu'un nombre exemple :





JTextField txt = new JTextField();

DigitModel model = new DigitModel();

..........



txt.setModel(model);



..........







public class DigitModel extends PlainDocument {



public DigitCaseDocument(){

super();

}



public void insertString(int offs, String str, AttributeSet a)

throws BadLocationException {



if (str == null) return;

String digit = "";

for (char c : str.toCharArray())

if (Character.isDigit(c)) digit += c;

else {



Toolkit.getDefaultToolkit().beep();

break;

}

super.insertString(offs, digit, a);

}

}


WORA
0
Rejoignez-nous