0

I need to restrict a text field input to just digits, comma and dots. I could do this using a DocumentFilter and a JTextField but what if I wanted to use a JFormattedTextField?

I've tried to look at some examples but I didn't understand.

JessicaJ
  • 31
  • 5
  • Have you read this Oracle tutorial as part of your examples? [How to Use Formatted Text Fields](https://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html) – Obicere Jun 21 '18 at 00:04
  • Yes, but it works only for digits. Doesn't work with commas and dots. – JessicaJ Jun 21 '18 at 00:11
  • There are a lot of examples on there to go off of. You can then simply call [MaskFormatter#setValidCharacters(String)](https://docs.oracle.com/javase/8/docs/api/javax/swing/text/MaskFormatter.html#setValidCharacters-java.lang.String-). This is by far the easiest way to accomplish what you want. I posted that link because I assumed there would be a mention of this, but I guess not. – Obicere Jun 21 '18 at 00:17
  • Ok, now it works but how can I avoid to set a mask? I just want to set the valid characters. I've tried this `MaskFormatter formatter = new MaskFormatter(); formatter.setValidCharacters("0123456789,.");` but doesn't work. – JessicaJ Jun 21 '18 at 00:56
  • Is there a strict character limit you can use? – Obicere Jun 21 '18 at 00:57
  • I could but I'd rather not. – JessicaJ Jun 21 '18 at 00:59
  • 1
    `I just want to set the valid characters.` - why? `now it works but how can I avoid to set a mask?` - so you have your answer, why are you trying to make using the formatted text field so complicated? What is the problem with using the mask that you are trying to solve? – camickr Jun 21 '18 at 03:01
  • @camickr by setting a mask the textfield doesn't work properly. It's like split the text field into cells and doesn't allow me to put text unless I click every time on a different cell. – JessicaJ Jun 21 '18 at 08:22

0 Answers0