JPasswordField là lớp con của JTextField và mỗi ký tự nhập vào sẽ được thay bằng ký tự echo. Điều này cho phép nhập mật khẩu bảo mật. Các phương thức quan trọng: getPassword(), getText(), getAccessibleContext(). Mặc định có thể nhập bất kỳ số ký tự nào. Để giới hạn, triển khai lớp DocumentFilter và ghi đè phương thức replace().
Cú pháp
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException
Ví dụ
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();
}
}
Kết quả
