Limiting and formatting a JTextfield

2019-03-04 08:13发布

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条回答
Rolldiameter
2楼-- · 2019-03-04 08:58

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

查看更多
登录 后发表回答