The JPasswordField
in Java Swing is a component used to create a field where the user can input sensitive information like passwords. The input is displayed as dots or asterisks to maintain security.
Following is an example of how to create and use a JPasswordField
in a Swing application:
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
public class PasswordFieldDemo {
public static void main(String[] args) {
// Create the JFrame
JFrame frame = new JFrame("Password Field Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 150);
// Create a panel to hold components
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2, 2));
// Create a label for the password field
JLabel passwordLabel = new JLabel("Password:");
panel.add(passwordLabel);
// Create the password field
JPasswordField passwordField = new JPasswordField();
panel.add(passwordField);
// Create a button to retrieve the password
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(e -> {
char[] passwordChars = passwordField.getPassword();
String password = new String(passwordChars);
JOptionPane.showMessageDialog(null, "Your password is: "+password);
});
panel.add(submitButton);
// Add the panel to the frame
frame.add(panel);
// Set the frame to be visible
frame.setVisible(true);
}
}
Output: