JTextField - Part 2
Technically this isn't a JTextField, but I feel the JPasswordField is too small to warrant it's own lesson. It still is a very important part of the Swing Toolkit. Let's show you why.
I won't post the entire code this time, we are changing very little in the previous examples code. If you want to have a copy of the full listing of code in a separate page,
click here.
| TextField Example |
|
PasswordField Example |
60
61
62
63
| loginField = new JTextField(8);
loginField.setLocation(0, 40);
loginField.setSize(100, 30);
panelForTextFields.add(loginField);
| |
|
61
62
63
64
65
| loginField = new JPasswordField(8);
loginField.setEchoChar('&');
loginField.setLocation(0, 40);
loginField.setSize(100, 30);
panelForTextFields.add(loginField);
| |
The code on the right is replacing the code on the left. There is very little difference, other than we make the Field a JPasswordField.
By default, the echo char (the thing that comes up when you type) is an asterisk ('*'), but I have set it here to '&'.
When you type in the Password box, the characters displayed are "&&&&&&" instead of "Robert".

In the actionPerformed method, we must carry out a different procedure to get the text from the JPasswordField.
130
131
132
133
134
135
136
137
138
139
140
141
| char[] answer = {'R', 'o', 'b', 'e', 'r', 't'};
char[] input = loginField.getPassword();
if(Arrays.equals(input, answer))
{
passLabel.setForeground(Color.green);
passLabel.setText("Correct!");
for(int i = 0; i < input.length; i++)
{
input[i] = ' ';
}
}
|
We get the password by using .getPassword() on the JPasswordField (line 130). This returns a character array.
Instead of storing the correct password as a string, we store it for ease as another character array.
We can then compare the two using Arrays.equals(). Remember to import the java.util.arrays; package at the start!
137
138
139
140
| for(int i = 0; i < input.length; i++)
{
input[i] = ' ';
}
|
Once we've got a correct answer, we wipe the character array containing the user-inputted correct answer. This is just for added security, so there isn't a clear-text version of the password sitting on the memory. Obviously we'd encrypt the password we compare to. This is rather than leaving it in clear text on the file, or store it elsewhere like in a database.
Anything you can do with JTextField you can do with JPasswordField as the password field is a subclass of JTextField.

Do you do PasswordFields?