Java: how to delete spaces in jformattedtextfield?
So I have a jformattedtextfield that lets users enter a number The number can be 1 to 99, so I used maskformatter ("##") However, for some reason, if I don't enter anything, it will place 2 spaces in the text field This is annoying because if the user clicks on the center of the text field to enter a number, it will place the cursor at the end of the 2 spaces (because the spaces are shorter than the numbers), so they must return to place the number
How do I delete these spaces and leave the text field blank? I tried to do settext (""), but it didn't do anything
This 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); }
Solution
Your MF Install (sequencejtf) the following Java core contains the following code:
... ftf.setText(valueToString(ftf.getValue())); // ftf - jformattedtextfield ...
Valuetostring() returns two spaces if there are no characters to match the mask "##" Spaces are taken from maskformatter Getplaceholdercharacter(), which returns a space as the default character
My solution is not that 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 }