Email JTextField in Swing: Ready made code

  

   Here’s a ready made Email text field written as a swing component. This text field allows the user to type any thing in it but does not allow the focus to go out of it unless whatever the user has typed is a valid email address. Note that extensive validation is not done. You can modify the code as you like. There are no restrictions. The code uses an input verifier to achieve this.

package kaushik.test;
 
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
 
public class EmailTextField extends JTextField{
  public EmailTextField(int columns){
    super(columns);
    addVerifier();
  }
 
  private void addVerifier(){
    this.setInputVerifier(new EmailVerifier());
  }
 
  class EmailVerifier extends InputVerifier{    
    public boolean verify(JComponent input) {
      String regx = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
      String text = EmailTextField.this.getText();
 
      if(text.matches(regx)){       
        return true;
      }
      else{
        JOptionPane.showMessageDialog(null, 
            "Invalid email format");
        return false;
      }
    }
  }
}






3 Responses to 'Email JTextField in Swing: Ready made code'

  1. Ready made Simple Custom TextField components » Java Swing - July 27th, 2008 at 8:01 am

    […] « Email JTextField in Swing: Ready made code […]

  2. Swing links of the week: July 27, 2008 : Pushing Pixels - July 28th, 2008 at 5:04 pm

    […] upper limit on the number of characters, auto-conversion to upper case, number-only content and e-mail content. For more background on using regular expressions in e-mail verification see this […]

  3. thangaduraisfui - October 19th, 2008 at 6:15 am

    please send me newsletter with code
    sufi
    chennai


Leave a Reply





Popular Articles

Blog Categories

Monthly Archives

Resources