Hey guys, I was wondering if there is anyway I can set a JFormattedTextField to have an auto format of an email input. For example, When the user type an e开发者_StackOverflow社区mail address I want it to accept something like this: jsmith1@smith.com
But I want it to always be like this name@site.something(net,com,edu)
basically i always want the '@' and '.'
I think your best bet is to subclass AbstractFormatter
and use a regexp for email, something like:
public class EmailFormatter extends AbstractFormatter {
@Override public Object stringToValue(String string) throws ParseException {
Matcher matcher = regexp.matcher(string);
if (matcher.matches())
return string;
throw new ParseException("Not an email", 0);
}
@Override public String valueToString(Object value) {
return value;
}
final private Pattern regexp = Pattern.compile("EMAIL REGEXP TO FIND BY YOURSELF");
}
...
JFormattedTextField email = new JFormattedTextField(new EmailFormatter());
Note that I let you discover the right regexp for an email; you can the easy way, or if you prefer, check one RFC that describes a one-page long regexp that covers emails as per the real specs, but maybe you can simplify your requirements ;-)
No easy way (that is, no such thing as JFormattedTextField.autoEmail()). But it wouldn't be hard to code something like this. In the field where the user presses a button or whatever to enter what's in the field, just don't accept the input if it doesn't have the @ and . characters. Either that or do a quick check to see if they included it, and if not, append it to the end.
精彩评论