Bitcoin

Bitcoin
Bitcoin

JPasswordField Java

JPasswordField is a subclass of the JTextField so it acts like an ordinary text field but it hides the actual characters typed by showing a series of echo characters such as asterisks (*) or a dots, for security purpose. For example:

In this article, we provide a summary of the common and recommended practices when working with JPasswordField in Swing, with code examples and a demo program.

JPasswordField class declaration

Let's see the declaration for javax.swing.JPasswordField class.
  1. public class JPasswordField extends JTextField  

Commonly used Constructors:

ConstructorDescription
JPasswordField()Constructs a new JPasswordField, with a default document, null starting text string, and 0 column width.
JPasswordField(int columns)Constructs a new empty JPasswordField with the specified number of columns.
JPasswordField(String text)Constructs a new JPasswordField initialized with the specified text.
JPasswordField(String text, int columns)Construct a new JPasswordField initialized with the specified text and columns.

A typical usage of JPasswordField looks like this:
1
2
3
4
5
6
7
8
// create new object
JPasswordField passwordField = new JPasswordField(20);
 
// add to the container
frame.add(passwordField);
 
// get the password
char[] password = passwordField.getPassword();
Let’s dive into more details.
 

1. Creating new JPasswordField object

When creating a new JPasswordField object, we can specify an initial text and the field’s width in number of columns, using one of the following constructors:
1
2
3
4
5
JPasswordField(int columns)
 
JPasswordField(String text)
 
JPasswordField(String text, int columns)
Note that the parameter columns specifies minimum width of the field in a number of columns, not in number of pixels nor characters. Here are some examples:
1
2
3
4
5
JPasswordField passwordField = new JPasswordField(20);
 
JPasswordField passwordField = new JPasswordField("secret");
 
JPasswordField passwordField = new JPasswordField("secret"20);

We can also use an empty constructor to create new object and then set the columns and initial password later, for example:
1
2
3
JPasswordField passwordField = new JPasswordField(20);
passwordField.setColumns(10);
passwordField.setText("secret");
NOTE: Like other Swing components, the JPasswordField class resides in the package javax.swing.
 


2. Adding the password field to a container

The password field cannot stand alone. It must be added to a parent container such as JFrame or JPanel. For example:
1
2
frame.add(passwordField);
panel.add(passwordField);
Adding to a JFrame with BorderLayout:
1
frame.add(passwordField, BorderLayout.NORTH);
Adding to a JFrame with GridBagLayout:
1
2
3
4
GridBagConstraints constraints = new GridBagConstraints();
// set constraints...
 
frame.add(passwordField, constraints);


3. Setting and getting password

Use the setText() method (inherited from javax.swing.text.JTextComponent class) to set password for the field:
1
passwordField.setText("secret");
To retrieve password typed into the field, use the getPassword() method:
1
char[] password = passwordField.getPassword();
For security purpose, the getPassword() method returns a char array instead of a String object. So it’s RECOMMENDED to compare the password as follows:
1
2
3
4
5
6
7
8
char[] password = passwordField.getPassword();
char[] correctPass = new char[] {'s''e''c''r''e''t'};
 
if (Arrays.equals(password, correctPass)) {
    System.out.println("Password is correct");
else {
    System.out.println("Incorrect password");
}
In the above code snippet, we use the method equals() of the java.util.Arrays class to compare two char arrays.
AVOID getting the password as follows:
1
String password = new String(passwordField.getPassword());
AVOID comparing the password as follows:
1
2
3
4
String password = new String(passwordField.getPassword());
if (password.equals("secret")) {
    // password is correct
}
It’s also recommended to clear the char array when we are finished using it (for enhanced security):
1
Arrays.fill(correctPass, '0');
NOTE: The getText() method is deprecated in JPasswordField class because it returns password as a String object which might be vulnerable for security.

4. Adding event listeners

We can add a listener for the event in which the user presses Enter key after typing text into the field. For example:
1
2
3
4
5
6
7
8
9
10
11
passwordField.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent event) {
        JPasswordField field = (JPasswordField) event.getSource();
        char[] password = field.getPassword();
 
        if (password.length < 8) {
            System.out.println("Password must contain at least 8 characters!");
        }
    }
});
The above code will check for length of the entered password as soon as the user hits Enter key.
We can also add a listener to handle key events which are fired whenever the user types a character into the field. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
passwordField.addKeyListener(new KeyListener() {
 
    @Override
    public void keyTyped(KeyEvent event) {
        // do something when a key has been typed
    }
 
    @Override
    public void keyReleased(KeyEvent event) {
        // do something when a key has been released
    }
 
    @Override
    public void keyPressed(KeyEvent event) {
        // do something when a key has been pressed
    }
});
A typical usage of key event listener is to check emptiness of the field in order to enable/disable the action button accordingly, for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
passwordField.addKeyListener(new KeyAdapter() {
    @Override
    public void keyReleased(KeyEvent event) {
        JPasswordField field = (JPasswordField) event.getSource();
        char[] password = field.getPassword();
 
        if (password == null || password.length == 0) {
            actionButton.setEnabled(false);
        else {
            actionButton.setEnabled(true);
        }
    }
});
Notice in the above code snippet, we create an anonymous class that extends the KeyAdapter class, instead of implementing the KeyListener interface, so we can override only the interested method.
 

5. Selecting text

Select all text in the field:
1
passwordField.selectAll();
The selection looks like this:

6. Customizing appearance

  • Set echo character:
    1
    passwordField.setEchoChar('*');

    Image:
Set font style, background and foreground colors: 
1
2
3
passwordField.setFont(new java.awt.Font("Arial", Font.BOLD, 20));
passwordField.setBackground(Color.YELLOW);
passwordField.setForeground(Color.BLUE);
Image:


  • Set tooltip text:
1
passwordField.setToolTipText("Password must contain at least 8 characters");

Java JPasswordField Example

  1. import javax.swing.*;    
  2. public class PasswordFieldExample {  
  3.     public static void main(String[] args) {    
  4.     JFrame f=new JFrame("Password Field Example");    
  5.      JPasswordField value = new JPasswordField();   
  6.      JLabel l1=new JLabel("Password:");    
  7.         l1.setBounds(20,10080,30);    
  8.          value.setBounds(100,100,100,30);    
  9.             f.add(value);  f.add(l1);  
  10.             f.setSize(300,300);    
  11.             f.setLayout(null);    
  12.             f.setVisible(true);     
  13. }  
  14. }  
Output:



Java JPasswordField Example with ActionListener

  1. import javax.swing.*;    
  2. import java.awt.event.*;  
  3. public class PasswordFieldExample {  
  4.     public static void main(String[] args) {    
  5.     JFrame f=new JFrame("Password Field Example");    
  6.      final JLabel label = new JLabel();            
  7.      label.setBounds(20,150200,50);  
  8.      final JPasswordField value = new JPasswordField();   
  9.      value.setBounds(100,75,100,30);   
  10.      JLabel l1=new JLabel("Username:");    
  11.         l1.setBounds(20,2080,30);    
  12.         JLabel l2=new JLabel("Password:");    
  13.         l2.setBounds(20,7580,30);    
  14.         JButton b = new JButton("Login");  
  15.         b.setBounds(100,12080,30);    
  16.         final JTextField text = new JTextField();  
  17.         text.setBounds(100,20100,30);    
  18.                 f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);  
  19.                 f.setSize(300,300);    
  20.                 f.setLayout(null);    
  21.                 f.setVisible(true);     
  22.                 b.addActionListener(new ActionListener() {  
  23.                 public void actionPerformed(ActionEvent e) {       
  24.                    String data = "Username " + text.getText();  
  25.                    data += ", Password: "   
  26.                    + new String(value.getPassword());   
  27.                    label.setText(data);          
  28.                 }  
  29.              });   
  30. }  
  31. }  
Output:


Facebook