-1

This is my code but it doesn't work,why?I use the RegexFormatter("@.*") but it seems doesn't work.it can't check the JFormattedTextField whether @.* contain or not.And I want to show the result at the verify label how should I do?

public class hw5 extends JFrame {

private JPanel contentPane;
private JPasswordField passwordField;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        public void run() {
            try {
                hw5 frame = new hw5();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
public hw5() {
    setTitle("hw5");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JFormattedTextField FormattedField = new JFormattedTextField(new RegexFormatter("*@*.*"));
}

    }
class RegexFormatter extends DefaultFormatter {
  private Pattern pattern;

  private Matcher matcher;

  public RegexFormatter() {
    super();
  }

public Object stringToValue(String text) throws ParseException {
Pattern pattern = getPattern();

if (pattern != null) {
  Matcher matcher = pattern.matcher(text);

  if (matcher.matches()) {
    setMatcher(matcher);
    return super.stringToValue(text);
  }
  throw new ParseException("Pattern did not match", 0);
}
return text;

} }

lee
  • 1
  • Please do not simply post your half-done homework and hope that someone fixes it for you. At least, tell us what the result of your attempts are, and what else you have tried. – miw Apr 03 '16 at 17:26
  • 1
    You could just do `text.contains("@");` :P – Laurel Apr 03 '16 at 17:32

1 Answers1

0

Your regex *@*.* if wrong. It means:

  • One *
  • Followed by zero or more @
  • Followed by zero or more characters (any)

Validating an e-mail via regex is very complicated (if you want to do it correctly). Since it seems all you want to do is check for "something with an @", I'd suggest the following regex:

[^@]+@[^@]+

Or better yet:

^[^@]+@.[^@]+$

It means:

  • ^: start of string
  • [^@]+: followed by one or more characters that are not @
  • @: a single @
  • [^@]+: followed by one or more characters that are not @
  • $

This will match a@b and alpha+beta$@^& but will fail on foo or a@b@c. Whether this is sufficient for you, I don't know. There are far better ways to validate whether an input is an e-mail address.

Community
  • 1
  • 1
DarkDust
  • 90,870
  • 19
  • 190
  • 224