JTextField Login Validation Example Java Swing


In the following program, user name and password are taken from user using JTextField and JPasswordField.
import javax.swing.*;  				        // for JTextField, JPasswordField, ImageIcon etc.
import java.awt.*;  					// for Container class
import java.awt.event.* ;  		             	// ActionEvent, ActionListener

public class TextAndPassValidation extends JFrame implements ActionListener
{
  JTextField tf1, tf2;
  JPasswordField pf ;
  public TextAndPassValidation( )
  {
    super("Learning text and password fields"); 	// instead of setTitle( )
    Container c = getContentPane();
    c.setLayout(new GridLayout(3, 2, 10, 10));

    tf1 = new JTextField(15);				 // for user name
    c.add(tf1);
		                     			 // using a constructor with a string and an integer as arguments
    tf2 = new JTextField("Sorry, U can not enter", 25);
    tf2.setEditable(false);                		 // user cannot enter anything in the text field (read-only)
    c.add(tf2);
                                                         // creating password field
    pf = new JPasswordField(10);
    c.add(pf);
		                                                     		        
                                                         // registering with the ActionListener
    pf.addActionListener(this);

    c.add(new JLabel("Enter User Name"));
    c.add(tf1);

    c.add(new JLabel("Enter Password"));
    c.add(pf);

    c.add(new JLabel("RESULT"));
    c.add(tf2);

    setSize(350,200);
    setVisible(true);
  }  
  public void actionPerformed(ActionEvent e)
  {
    String str1 = tf1.getText();  			// user name entered by the user
    String str2 = pf.getText();  			// password entered by the user
   						        // validation code
    if(str1.equalsIgnoreCase("snrao") && str2.equals("java"))
    {
      tf2.setText("VALID");
    }
    else
    {
      tf2.setText("INVALID");
    }
  }
  public static void main(String args[])
  {
    new TextAndPassValidation();
  }
}

JTextField

JTextField is equivalent to TextField of AWT. JPasswordField does not exist in AWT and is overcome with setEchoChar() method of TextField. JPasswordField is equivalent to HTML <input type=password>.

tf2.setEditable(false);

The JTextField tf2 is meant for the programmer to display the result of validation and not to the user to enter any text. To make the code user-friendly, the tf2 is made non-editable so that it is read-only.

String str1 = tf1.getText();
tf2.setText(“VALID”);

getText() and setText() are the methods of JTextField used to retrieve the text entered by the user and to display some text to the user.

1 thought on “JTextField Login Validation Example Java Swing”

Leave a Comment

Your email address will not be published.