I have a JFormattedTextField where the user would input prices, I have this, but if I type a character, it'll let me anyway. I need this text field to only read numbers or , from the keyboard, and ignore if it's a char. How should I change it in order to make it work?
JFormattedTextField formattedTextField = new JFormattedTextField();
formattedTextField.setBounds(25, 330, 56, 20);
contentPanel.add(formattedTextField);
formattedTextField.setValue(new Double(10.0));
You need to set a Formatter:
Take a look:
Format
and
NumberFormat
Then try this:
A
JFormattedTextField
can be used for many things, it can be also used to filter dates or phone numbers. You will either need to set aNumberFormater
to theTextField
or you use the DocumentFilter (works with JTextField only too).Check this code snippet, that's how you allow only digits in JTextField, by using DocumentFilter, as the most effeciive way :