ciao a tutti vorrei sapere se esiste un box in java che accetti in ingresso soltanto numeri.Quindi se l'utente prova ad inserire una stringa questo box non glielo permette,perchè può accettare solo numeri
ciao a tutti vorrei sapere se esiste un box in java che accetti in ingresso soltanto numeri.Quindi se l'utente prova ad inserire una stringa questo box non glielo permette,perchè può accettare solo numeri
<´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
"The answer to your question is: welcome to tomorrow"
seguendo ciò che dice il link che mi hai suggerito ho scritto
il problema è che riesco ad inserire nel boxSaldoIn soltanto un numero definito di cifre,ma questo non è un grande problema.Il problema è che mi permette di scrivere nel box a partire anche dalla terza cifra,ad esempio,e non dall'inizio del box.codice:MaskFormatter formatter=new MaskFormatter("###########"); boxSaldoIn = new JFormattedTextField(formatter);
Una via alternativa sarebbe quella di assegnare un Document personalizzato alla JTextField. Document e' l'oggetto che rappresenta il testo inserito nella tua JTextField. Sovrascrivendo l'apposito metodo, possiamo fare in modo che non inserisca caratteri non numerici.
codice:import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; public class NumberDocument extends PlainDocument { public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { if(str!=null && str.matches("[\\d]*")) super.insertString(offs, str, a); } }codice:JTextField testo = new JTextField(10); testo.setDocument(new NumberDocument());