-5

I am trying to automatically add a space between character groups in a TextTield.

When user enters 8 digits I want to insert a space between the first- and last four digits:

12345678 => 1234 5678

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74

1 Answers1

0

Try JFormattedTextField that allows you set an input mask.

MaskFormatter mask = null;
try {
    mask = new MaskFormatter("#### ####");
    mask.setPlaceholderCharacter(' ');
} catch (ParseException e) {
    e.printStackTrace();
}       
JFormattedTextField textfield = new JFormattedTextField(mask);
ArcticLord
  • 3,999
  • 3
  • 27
  • 47
  • Why the `try/catch` block if you don't handle the exception anyway? Can `JFormattedTextField` handle a `null` formatter? Does the code in that block even throw a `ParseException`? Why set a placeholder character when space is the default anyway? – Robert Dec 23 '15 at 14:32
  • `try/catch` block because MaskFormatter Constructor throws `ParseException` if syntax error in mask. And if it does and mask is `null` the resulting `JFormattedTextField` works and acts like normal `JTextField`. The placeholder is not necessary. I put it for demonstration. – ArcticLord Dec 23 '15 at 14:47