JPasswordField는 JTextField의 하위 클래스로, 사용자가 입력하는 각 문자가 에코(echo) 문자로 대체되어 화면에 표시됩니다. 이러한 특성 덕분에 비밀번호처럼 민감한 정보를 노출하지 않고 안전하게 입력받을 수 있습니다. JPasswordField의 주요 메서드로는 getPassword(), getText(), getAccessibleContext() 등이 있습니다.
기본 설정 상태에서는 JPasswordField 안에 글자 수 제한 없이 원하는 만큼 입력할 수 있습니다. 만약 사용자가 입력할 수 있는 글자 수를 제한하고 싶다면 DocumentFilter 클래스를 구현하고 그 안에서 replace() 메서드를 오버라이드(재정의)해야 합니다.
구문(Syntax)
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException예제 코드
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();
}
}코드 설명
위 예제는 4자리 PIN 번호를 입력받는 화면을 구성합니다. 핵심은 passwordField의 문서(Document)에 setDocumentFilter() 메서드로 필터를 등록하는 부분입니다. 익명 클래스 형태로 생성한 DocumentFilter에서 replace() 메서드를 재정의하여, 현재 문서에 저장된 전체 텍스트와 새로 입력된 텍스트를 합친 길이가 4자 이하일 때만 super.replace()를 호출하도록 처리했습니다.
이 로직 덕분에 이미 4글자가 입력된 상태에서 추가로 문자를 입력하려고 하면 해당 입력은 무시되어 차단됩니다. 붙여넣기(Paste) 작업에도 동일하게 적용되므로, 입력 길이를 강제로 통제해야 하는 PIN 번호나 인증 코드 입력란에 유용하게 활용할 수 있습니다.
실행 결과
