Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: AWT
Expertise: Beginner
Mar 20, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Creating TextField to Handle Passwords

How do I create a TextField that handles a password? What are the KEY_ACTION events associated with it?

The setEchoCharacter() method within the TextField class allows you to do precisely that. It lets you specify the character that is to display on the screen within the textfield area when the user types something in it. So if you set that character to something like '*', the password doesn't appear on the screen. For example, the following applet creates a name and password prompt. For the user name, the characters are echoed back normally, but for the password only asterisks appear. To know when the user is done entering a password, you can simply watch for ACTION_EVENT events in the action() method of the applet.

import java.applet.*;
import java.awt.*;

public class PasswordPrompt extends Applet {
       TextField username, password;

       public void init() {
               setLayout(new BorderLayout());

               // add a username text field

               Panel namePanel = new Panel();
               Label nameLabel = new Label("User name: ");
               username = new TextField(20);
               add("North", namePanel);

               // add a password text field

               Panel pwPanel = new Panel();
               Label pwLabel = new Label("Password: ");
               password = new TextField(20);

               // set the echo character to be an asterisk

               add("South", pwPanel);

       public synchronized boolean action(Event e, Object what) {
               if (e.target == password && e.id == Event.ACTION_EVENT) {

                       // the user has pressed enter in the password
                       // text field.  You can choose to catch ACTION_EVENTs
                       // for the username area as well.

                       showStatus("User: " + username.getText() +
                                       ", Password: " + password.getText());
                       return true;
               return false;
DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date