Utilizzo il seguente codice per limitare a 10 il numero di numeri inseriti in un jtextfield
pero' ho il seguente problema
se uno digita 11 cifre di file, il codice funziona nel senso che impedisce l'inserimento dell'undicesima cifra
se uno digita 10 cifre di fila e poi mette il cursore in cima alla riga (o a metà riga) del campo jtextfield, queto codice permette l'inserimento dell'undicesimo carattere
come posso fare per impedirlo?
codice:public class LimitNumberDocument extends PlainDocument { private static final long serialVersionUID = -6829435640064907333L; private int max_length = 0; int max_length = 10; public LimitNumberDocument() { } public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { String strTemp = new String(str); while (strTemp.length() >= 1) { String charAtIndexZero = strTemp.substring(0, 1); if (charAtIndexZero.hashCode() < 47 || charAtIndexZero.hashCode() > 57) { System.err.println("Sono ammessi solo numeri ed il carattere /: " + strTemp + " hashcode: " + strTemp.hashCode()); return; } strTemp = strTemp.substring(1); } int chNumberInsert = getText(0, offs).length(); int chNumberToInsert = str.length(); int chNumberMax = chNumberInsert + chNumberToInsert; if (chNumberMax <= max_length) super.insertString(offs, str, a); else System.err.println("Non è possibile inserire più di " + max_length + " cifre"); } }

Rispondi quotando

