0

I have jtextfield textFoo in which i want user input. I want to allow to input only numbers and it must be 6 characters long.I did try the code below but it often have already blank characters written and i must delete them before writing. The textFoo textfield also is deleting numbers when it lose focus,why it doing this ? And how to get rid of this blank characters at the beginning? Or is there better way to limit user input to 6 numeric characters?

textFoo = new JFormattedTextField(createFormatter("######"));
textFoo.setBounds(92, 29, 86, 20);
textFoo.setVisible(true);
add(textFoo);

....    

private MaskFormatter createFormatter(String s) {
MaskFormatter formatter = null;
try {
    formatter = new MaskFormatter(s);
} catch (java.text.ParseException exc) {
    System.err.println("fooText :" + exc.getMessage());
}
return formatter;
}
Majlena
  • 103
  • 1
  • 9
  • 2
    `DocumentFilter`, `DocumentFilter`, `DocumentFilter`, see [Implementing a Document Filter](http://docs.oracle.com/javase/tutorial/uiswing/components/generaltext.html#filter) and [DocumentFilter Examples](http://www.jroller.com/dpmihai/entry/documentfilter) for more details – MadProgrammer Mar 14 '16 at 11:26
  • 1
    @Prashant Using a custom `Document` is no longer (since Java 1.4) the best solution to this problem, while it stated somewhere among one of the answers, it's not the top rated answer, you should be using a `DocumentFilter` instead – MadProgrammer Mar 14 '16 at 11:27

0 Answers0