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:
JPasswordField class declaration
Let's see the declaration for javax.swing.JPasswordField class.
Commonly used Constructors:
| Constructor | Description |
|---|---|
| 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
2
3
4
5
6
7
8
| // create new objectJPasswordField passwordField = new JPasswordField(20);// add to the containerframe.add(passwordField);// get the passwordchar[] password = passwordField.getPassword(); |
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);
1
2
3
4
5
| JPasswordField(int columns)JPasswordField(String text)JPasswordField(String text, int columns) |
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.
1
2
3
| JPasswordField passwordField = new JPasswordField(20);passwordField.setColumns(10);passwordField.setText("secret"); |
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);
1
2
| frame.add(passwordField);panel.add(passwordField); |
1
| frame.add(passwordField, BorderLayout.NORTH); |
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.
1
| passwordField.setText("secret"); |
1
| char[] password = passwordField.getPassword(); |
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");} |
1
| String password = new String(passwordField.getPassword()); |
1
2
3
4
| String password = new String(passwordField.getPassword());if (password.equals("secret")) { // password is correct} |
1
| Arrays.fill(correctPass, '0'); |
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!"); } }}); |
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 }}); |
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); } }}); |
5. Selecting text
Select all text in the field:
1
| passwordField.selectAll(); |
6. Customizing appearance
- Set echo character:1
passwordField.setEchoChar('*');
Image:
Set font style, background and foreground colors:
Image:
1
2
3
| passwordField.setFont(new java.awt.Font("Arial", Font.BOLD, 20));passwordField.setBackground(Color.YELLOW);passwordField.setForeground(Color.BLUE); |
- Set tooltip text:
1
| passwordField.setToolTipText("Password must contain at least 8 characters"); |
Java JPasswordField Example
Output:
Java JPasswordField Example with ActionListener
Output:




No comments:
Post a Comment