JPasswordField เป็นคลาสย่อยของ JTextField ตัวอักษรที่พิมพ์จะถูกแทนที่ด้วย echo character เพื่อความปลอดภัยรหัสผ่าน เมธอดสำคัญ ได้แก่ getPassword(), getText(), getAccessibleContext() โดยปกติพิมพ์ได้ไม่จำกัด หากต้องการจำกัด ใช้ DocumentFilter class และ override เมธอด replace()
ไวยากรณ์
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException
ตัวอย่าง
import java.awt.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class JPasswordFieldDigitLimitTest extends JFrame {
private JPasswordField passwordField;
private JPanel panel;
public JPasswordFieldDigitLimitTest() {
panel = new JPanel();
((FlowLayout) panel.getLayout()).setHgap(2);
panel.add(new JLabel("Enter Pin: "));
passwordField = new JPasswordField(4);
PlainDocument document = (PlainDocument) passwordField.getDocument();
document.setDocumentFilter(new DocumentFilter() {
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
String string = fb.getDocument().getText(0, fb.getDocument().getLength()) + text;
if (string.length() <= 4) {
super.replace(fb, offset, length, text, attrs);
}
}
});
panel.add(passwordField);
add(panel);
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JPasswordFieldDigitLimitTest();
}
}
ผลลัพธ์
