JPasswordField Example
This JPasswordField example shows how to display a password request and how to receive the password. It asks the user for a password and then outputs the password.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// JPasswordField Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class JPasswordFieldExample {
public static void main(String[] args) {
final JPasswordField pw = new JPasswordField(10);
pw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(new String(pw.getPassword()));
}
});
JFrame jframe = new JFrame();
Container cp = jframe.getContentPane();
cp.setLayout(new FlowLayout());
JLabel jlabel = new JLabel("Enter your password and hit RETURN");
cp.add(jlabel);
cp.add(pw);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}
}
10 A JPasswordField accepting 10 characters is constructed.
12 An ActionListener is added to the JPasswordField.
14 When the user has entered the password an actionPerformed() event happens which enables the program to retrieve the password. The JPasswordField.getPassword() method returns a char[], a character array, of the password entered. This can be used as a parameter to a String constructor. Finally the value is output.
