TextField User Name Password Validation


After Button, the most used AWT component is TextField. TextField is useful to take input from the user and also to display output to the user by the programmer. User can write and edit the text in the TextField. Programmatically, the TextField can be made non-editable. Pressing Enter key generates ActionEvent and can be handled by ActionListener.

Limitations of TextField

One small limitation of TextField is it allows entering or displaying only one line of text; of course of any length. Anyhow, this limitation is overcome with TextArea, another AWT component.

Following is the class signature

public class TextField extends TextComponent

The super class of TextField is TextComponent and also for TextArea.

Example code on TextField User Name Password Validation

The following program comes with 3 text fields. In two text fields, user enters name and password. In the third text field, the programmer displays the result of validation.

import java.awt.*;
import java.awt.event.*;
public class UserPassValidation extends Frame implements ActionListener
{
  TextField nameField, passField, resultField;
  Label lab1, lab2, lab3;
  public UserPassValidation()
  {                       // set layout
    setLayout(new GridLayout(3, 2, 0, 10));  
    setBackground(Color.pink);  // fill the gap with color
                         // create components
    nameField = new TextField(15);
    passField = new TextField(15);
    resultField = new TextField(15);
    lab1 = new Label("Enter User Name");
    lab2 = new Label("Enter Password");
    lab3 = new Label("Display Result");
    	             // register the listener
    passField.addActionListener(this);
    	            // beautification
    passField.setEchoChar('*');
    resultField.setEditable(false);

    add(lab1);   add(nameField);
    add(lab2);   add(passField);
    add(lab3);   add(resultField);

    setTitle("User Name & Password Validation");
    setSize(300, 300);
    setVisible(true);
   }
   public void actionPerformed(ActionEvent e)
   {                   // get the values entered by the user
     String str1 = nameField.getText();
     String str2 = passField.getText();
                        // some validation code
     if(str1.equals("snrao") && str2.equals("java"))
     {
       resultField.setText("VALID");
     }
     else
     {
       resultField.setText("INVALID, TRY AGAIN");
     }
   }
   public static void main(String args[])
   {
     new UserPassValidation();
   }
}

TextField User Name Password Validation

7 thoughts on “TextField User Name Password Validation”

  1. I have a question , if I enter any value in textfied then I want another value will be come in another textfield based on previous text field. using awt frame in java
    and another question is how to add print facility on a button click .
    i have done printing work but it give low quality print ..

Leave a Comment

Your email address will not be published.