Limiting and formatting a JTextfield

2019-03-04 08:04发布

问题:

I have a JTextfield where a user enters a "social security number". The SSN has 9 digits and 2 dashes for a total of 11 characters.

How do I limit the JTextField to 11 characters and also have 2 dashes in the textfield at the 4th and 7th position of the 11 characters?

回答1:

You might want to use : JFormattedTextField

See this for more help : How to Use Formatted Text Fields

Also this might help : MaskFormatter

Here is a sample snippet :

MaskFormatter formatter = new MaskFormatter("####-###-####");

EDIT :

After some research I found out that a DocumentFilter would do things better,

See this for more details : Implementing a Document Filter