JPasswordField
🔐 Java Swing JPasswordField – Overview & Example
JPasswordField is a subclass of JTextField in Swing used for password input. The characters are masked (e.g., shown as * or •) for security.
✅ Key Features
| Method / Property | Description |
|---|---|
setEchoChar(char) |
Sets the masking character |
getPassword() |
Returns the password as a char[] |
setText(String) |
Sets the text (not recommended for passwords) |
getText() |
Returns the text (deprecated for passwords) |
✅ Example: Basic Password Field
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PasswordExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JPasswordField Example");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JLabel label = new JLabel("Enter Password:");
JPasswordField passwordField = new JPasswordField(15);
JButton button = new JButton("Submit");
JLabel result = new JLabel();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
char[] password = passwordField.getPassword();
String passString = new String(password);
result.setText("Password: " + passString);
}
});
frame.add(label);
frame.add(passwordField);
frame.add(button);
frame.add(result);
frame.setVisible(true);
}
}
🔒 Security Tips
-
Always use
getPassword()instead ofgetText()to avoid keeping passwords in memory longer than necessary. -
Clear the
char[]array after use (Arrays.fill(password, '0');). -
Avoid storing passwords in
Stringform if security matters.
Would you like to combine JPasswordField with login validation?
Comments
Post a Comment