2011-05-15 42 views

回答

0

沒有簡單的方法(也就是說,沒有像JFormattedTextField.autoEmail()這樣的事情)。但是編寫這樣的代碼並不困難。在用戶按下按鈕或輸入字段中的內容的字段中,如果它沒有@和則不接受輸入。字符。或者做一個快速檢查,看看是否包含它,如果沒有,則將其追加到最後。

3

我認爲最好的方法是繼承AbstractFormatter,並使用正則表達式的電子郵件,是這樣的:

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()); 

請注意,我讓你發現了一封電子郵件,右邊的正則表達式;你可以簡單的方式,或者如果你願意,檢查一個RFC描述了一個單頁長的正則表達式,涵蓋了電子郵件的真實規格,但也許你可以簡化你的要求;-)