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);
}