Creating TextField to Handle Passwords

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

Answer:
The setEchoCharacter() method within the TextField class allows youto do precisely that. It lets you specify the character that isto display on the screen within the textfield area when the usertypes something in it. So if you set that character to somethinglike ‘*’, the password doesn’t appear on the screen.For example, the following applet creates a name and passwordprompt. For the user name, the characters are echoed back normally, butfor the password only asterisks appear. To know when theuser is done entering a password, you can simply watch for ACTION_EVENTevents 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: “);               namePanel.add(nameLabel);               username = new TextField(20);               namePanel.add(username);               add(“North”, namePanel);               // add a password text field               Panel pwPanel = new Panel();               Label pwLabel = new Label(“Password: “);               pwPanel.add(pwLabel);               password = new TextField(20);               // set the echo character to be an asterisk               password.setEchoCharacter(‘*’);               pwPanel.add(password);               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;       }}

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: