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
| public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField field = new JTextField();
((AbstractDocument)field.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
string=filter(string);
if ( string.length()>0 ) { // s'il n'y plus rien dans la chaine, on ne fait rien
super.insertString(fb, offset, string, attr);
}
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs)
throws BadLocationException {
String string = filter(text);
if ( string.length()>0 ) { // remplace uniquement par les caractères non chiffre
//if (string.equals(text)) { // interdit tout remplacement s'il y a au moins un chiffre
super.replace(fb, offset, length, text, attrs);
}
}
private String filter(String string) {
StringBuilder sb=new StringBuilder();
boolean beep=false;
for(int i=0;i<string.length();i++) {
char c=string.charAt(i);
if ( Character.isDigit(c) ) {
beep=true;
}
else {
sb.append(c);
}
}
if ( beep ) {
Toolkit.getDefaultToolkit().beep();
}
return sb.toString();
}
});
frame.add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} |
Partager