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
|
public class CustomTextField extends JTextField
{
public CustomTextField()
{
super();
}
@Override
protected Document createDefaultModel()
{
return new FileCaseDocument();
}
static class FileCaseDocument extends PlainDocument
{
boolean canInsert = false;
String text = null;
String str1, str2;
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException
{
if (str == null || this.getLength()>=20) // pas plus de 20 caractères
{
return;
}
// pour gérer les copier-coller ou les insertions de nombres dans le champ
text = this.getText(0, this.getLength());
str1 = text.substring(0, offs);
str2 = text.substring(offs, this.getLength());
text = str1+str+str2;
// on autorise uniquement les entiers positifs et négatifs
canInsert = text.matches( "(-[1-9][0-9]*)|(0)|([1-9][0-9]*)" );
// nombre négatifs : on autorise le signe "-"
if (str.compareTo("-")==0 && this.getLength()==0)
{
canInsert = true;
}
if (canInsert)
{
super.insertString(offs, str, a);
}
}
}
} |
Partager