Grazie per l'aiuto. Nel frattempo io ho risolto così:
una volta dati in input lunghezza totale del numero e numero di decimali presenti al document aggiunto al textfield, effettuo dei controlli sugli inserimenti.
Ecco il codice della classe che estende PlainDocument. Spero possa servire a qualcuno.
codice:
public class TipoNumeroDecimale extends PlainDocument{
private int maxChars;
private int decimal;
public TipoNumeroDecimale(int lunghezza, int decimali){
maxChars=lunghezza+1;
decimal=decimali;
}
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
boolean continua = true;
if (str.equals(".")){
if (getText(0, getLength()).indexOf(".") == -1) {
super.insertString(offs, str, a);
}
return;
}
try {
if (str.indexOf(".") != -1){
Double.parseDouble(str);
}
else
Integer.parseInt(str);
} catch (NumberFormatException e) {
continua = false;
}
if (continua) {
int length = getLength();
if (length + str.length() <= maxChars) {
String somma = getText(0, length) + str;
if (str.length() == 1) {
if (somma.indexOf(".") != -1) {
if (offs > somma.indexOf(".") &
decimal < somma.substring(somma.indexOf(".") + 1).length()) {
return;
}
if (offs <= somma.indexOf(".") &
maxChars -
decimal - 1 <
somma.substring(0, somma.indexOf(".") + 1).length()) {
return;
}
super.insertString(offs, str, a);
}
else{
if (maxChars - decimal - 1 < somma.length()) {
return;
}
super.insertString(offs, str, a);
}
}
else {
super.insertString(offs, str, a);
}
}
else {
int allowed = maxChars - length;
super.insertString(offs, str.substring(0, allowed), a);
}
}
}
}