Download the JDK
Search the Tutorials
Hide the TOC
Trail: Creating a GUI with JFC/Swing
Lesson: Using Swing Components
Section: How to Use Various Components
Using Swing Components
A Visual Index to the Swing Components
Using HTML in Swing Components
Using Top-Level Containers
Using Models
The JComponent Class
Using Text Components
Text Component Features
The Text Component API
How to Use Various Components
How to Make Applets
How to Use Buttons, Check Boxes, and Radio Buttons
How to Use Color Choosers
How to Use Combo Boxes
How to Make Dialogs
How to Use Editor Panes and Text Panes
How to Use File Choosers
How to Use Formatted Text Fields
How to Make Frames (Main Windows)
How to Use Internal Frames
How to Use Labels
How to Use Layered Panes
How to Use Lists
How to Use Menus
How to Use Panels
How to Use Password Fields
How to Use Progress Bars
How to Use Root Panes
How to Use Scroll Panes
How to Use Separators
How to Use Sliders
How to Use Spinners
How to Use Split Panes
How to Use Tabbed Panes
How to Use Tables
How to Use Text Areas
How to Use Text Fields
How to Use Tool Bars
How to Use Tool Tips
How to Use Trees
How to Use Icons
How to Use Borders
Solving Common Component Problems
Home Page > Creating a GUI with JFC/Swing > Using Swing Components
« Previous • Trail • Next »
How to Use Password Fields

> The `JPasswordField` class, a subclass of `JTextField`, provides text fields specialized for password entry. For security reasons, a password field doesn't show the characters the user types. Instead, the field displays another character such as an asterisk '*'. As another security precaution, a password field stores its value as an array of characters, rather than as a string. Like an ordinary text field, a password field fires an action event when the user indicates that text entry is complete, such as by pressing the Enter button.

> Here's a picture of a demo that brings up a small window and prompts the user to type in a password.

> You can run PasswordDemo (it requires release 6) using JavaTM Web Start. (The password is "bugaboo".) The source code is in ``PasswordDemo.java``. Here's the code that creates and sets up the password field:

> >     passwordField = new JPasswordField(10);
> >     passwordField.setActionCommand(OK);
> >     passwordField.addActionListener(this);

> The argument passed into the `JPasswordField` constructor indicates the preferred size of the field — at least 10 columns wide, in this case. By default a password field displays a dot for each character typed. Calling `setEchoChar` allows it to be changed to another character. Finally, the code adds an action listener to the password field, which checks the value typed in by the user. Here's the implementation of the action listener's `actionPerformed` method:

> >     public void actionPerformed(ActionEvent e) {
> >         String cmd = e.getActionCommand();

> >         if (OK.equals(cmd)) { //Process the password.
> >             char[] input = passwordField.getPassword();
> >             if (isPasswordCorrect(input)) {
> >                 JOptionPane.showMessageDialog(controllingFrame,
> >                     "Success! You typed the right password.");
> >             } else {
> >                 JOptionPane.showMessageDialog(controllingFrame,
> >                     "Invalid password. Try again.",
> >                     "Error Message",
> >                     JOptionPane.ERROR_MESSAGE);
> >             }

> >             //Zero out the possible password, for security.
> >             for (int i = 0; i < input.length; i++) {
> >                 input[i] = 0;
> >             }

> >             passwordField.selectAll();
> >             resetFocus();
> >         } else ...//handle the Help button...
> >     }

> > Security note: Although the `JPasswordField` class inherits the `getText` method, you should use the `getPassword` method instead. Not only is `getText` less secure, but in the future it might return the visible string (for example, `"******"`) instead of the typed-in string.

> > To further enhance security, once you are finished with the character array returned by `getPassword`, you should set each of its elements to zero. The preceding code snippet shows how to do this.

> A program using a password field typically validates the password before completing any actions requiring the password. This program calls a private method, `isPasswordCorrect`, that compares the value returned by `getPassword` to a value stored in a character array. Here is its code:

> >     private static boolean isPasswordCorrect(char[] input) {
> >         boolean isCorrect = true;
> >         char[] correctPassword = { 'b', 'u', 'g', 'a', 'b', 'o', 'o' };

> >         if (input.length != correctPassword.length) {
> >             isCorrect = false;
> >         } else {
> >             for (int i = 0; i < input.length; i++) {
> >                 if (input[i] != correctPassword[i]) {
> >                     isCorrect = false;
> >                 }
> >             }
> >         }

> >         //Zero out the password.
> >         for (int i = 0; i < correctPassword.length; i++) {
> >             correctPassword[i] = 0;
> >         }

> >         return isCorrect;
> >     }

### The Password Field API

> The following tables list the commonly used `JPasswordField` constructors and methods. For information on the API password fields inherit, see How to Use Text Fields.

> Commonly Used JPasswordField Constructors and Methods
> Constructor or Method | Purpose
> --- | ---
> JPasswordField() JPasswordField(String) JPasswordField(String, int) JPasswordField(int) JPasswordField(Document, String, int) | Create a password field. When present, the `int` argument specifies the desired width in columns. The `String` argument contains the field's initial text. The `Document` argument provides a custom model for the field.
> char[] getPassword() | Set or get the text displayed by the password field.
> void setEchoChar(char) char getEchoChar() | Set or get the echo character — the character displayed instead of the actual characters typed by the user.
> void addActionListener(ActionListener) void removeActionListener(ActionListener) (defined in `JTextField`) | Add or remove an action listener.
> void selectAll() (defined in `JTextComponent`) | Select all characters in the password field.

### Examples that Use Password Fields

> PasswordDemo is the Tutorial's only example that uses a `JPasswordField` object. However, the Tutorial has many examples that use `JTextField`s, whose API is inherited by `JPasswordField`. See Examples that Use Text Fields for further information.

« Previous • Trail • Next »
Previous page: How to Use Panels
Next page: How to Use Progress Bars