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);
sequenceJTF = new JFormattedTextField(format);
try {
MaskFormatter mf = new MaskFormatter("##");
mf.install(sequenceJTF);
} catch (ParseException e) {}
sequenceJTF.setPreferredSize(new Dimension(20,20));
container.add(sequenceLabel);
container.add(sequenceJTF);
this.setContentPane(container);
}
source
share