4

So, I've got a JFormattedTextField to let the user enter a number. The number can be from 1 to 99, so I used a MaskFormatter("##"). However, for some reason it puts 2 spaces in the text field if I enter nothing. It's annoying because if the user clicks in the center of the text field to enter the numbers, it puts the cursor at the end of the 2 spaces (because spaces are shorter than numbers) and so they have to go back to put the number.

How do I remove those spaces and keep the textfield empty? I tried to do setText("") but it doesn't do anything.

Here's the code:

private JFormattedTextField sequenceJTF = new JFormattedTextField();
private JLabel sequenceLabel = new JLabel("Enter a number :");

public Window(){
      this.setTitle("Generic title");
      this.setSize(350, 250);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      this.setLocationRelativeTo(null);
      this.setVisible(true);

      JPanel container = new JPanel();


      DefaultFormatter format = new DefaultFormatter();
      format.setOverwriteMode(false); //prevents clearing the field if user enters wrong input (happens if they enter a single digit)
      sequenceJTF = new JFormattedTextField(format);
      try {
          MaskFormatter mf = new MaskFormatter("##");
          mf.install(sequenceJTF); //assign the maskformatter to the text field
      } catch (ParseException e) {}
      sequenceJTF.setPreferredSize(new Dimension(20,20));
      container.add(sequenceLabel);
      container.add(sequenceJTF);
      this.setContentPane(container);
  }
Zezombye
  • 321
  • 4
  • 16

1 Answers1

0

There is the next code in java core under yours mf.install(sequenceJTF);:

...
ftf.setText(valueToString(ftf.getValue())); // ftf - JFormattedTextField
...

where valueToString() returns two spaces if there is no characters, for matching the mask "##". Spaces are taken from MaskFormatter.getPlaceholderCharacter() which returns space as default char.

My solution is not so good, but it works:

try {
    MaskFormatter mf = new MaskFormatter("##") {
        @Override
        public char getPlaceholderCharacter() {
            return '0'; // replaces default space characters with zeros
        }
    };
    mf.install(sequenceJTF); //assign the maskformatter to the text field
} catch (ParseException e) {
    e.printStackTrace(); // always, remember, ALWAYS print stack traces
}
SeniorJD
  • 6,946
  • 4
  • 36
  • 53