Bonjour,
J'ai un soucis pour obtenir un JTextField dont la saisie ne dépasse pas une limite fixée.
Il ne s'agit pas de limiter le nombre de caractères, mais plutot de limiter la taille de la chaine.
"wwwwwwww" --> 8 caractères
"lllllllllllllllllllllllllllll" --> 29 caractères
J'ai utilisé un modèle de document avec vérification de la taille de la chaine, mais ça ne marche pas, quelqu'un a-t'il une idée ?
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 public class CustomText extends JTextField { CustomText(int limitString) { super(); Font f = new Font("Verdana", Font.PLAIN, 10); this.setFont(f); this.setDocument(new DocLimit(limitString, f)); } class DocLimit extends PlainDocument { private int limitStr; private FontMetrics fm; DocLimit(int limitS, Font f) { super(); limitStr = limitS; fm = getFontMetrics(f); } public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { if (str == null) return; if (fm.stringWidth(this.getText(0, getLength())) <= limitStr){ super.insertString(offset, str, attr); } else Toolkit.getDefaultToolkit().beep(); } }
Partager