JPasswordField JTextField 의 하위 클래스입니다. JPasswordField에 입력된 각 문자는 echo 로 대체될 수 있습니다. 캐릭터. 이것은 암호에 대한 기밀 입력을 허용합니다. JPasswordField의 중요한 메소드는 getPassword(), getText(), getAccessibleContext()입니다. 등. 기본적으로 JPasswordField 내부에 임의의 숫자를 입력할 수 있습니다. DocumentFilter 클래스 를 구현하여 사용자가 입력한 숫자를 제한하려는 경우 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();
}
} 출력
