Java: How to remove spaces in JFormattedTextField?

So, I have the JFormattedTextFielduser enter a number. The number can be from 1 to 99, so I used MaskFormatter("##"). However, for some reason, it puts 2 spaces in the text box if I don't enter anything. This is annoying because if the user clicks in the center of the text field to enter numbers, he places the cursor at the end of the two spaces (because spaces are shorter than numbers), and therefore they must come back to put the number.

How to remove these spaces and leave textfieldblank? I tried to do setText("")but does nothing.

Here is 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);
  }
+4
source share
1 answer

mf.install(sequenceJTF);:

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

valueToString() , , "##". MaskFormatter.getPlaceholderCharacter(), char.

, :

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
}
0

Source: https://habr.com/ru/post/1628816/


All Articles