How to restrict the number of digits inside JPasswordField in Java?


A JPasswordField is a subclass of JTextField and each character entered in a JPasswordField can be replaced by an echo character. This allows confidential input for passwords. The important methods of JPasswordField are getPassword(), getText(), getAccessibleContext() and etc. By default, we can enter any number of digits inside JPasswordField. If we want to restrict the digits entered by a user by implementing a DocumentFilter class and need to override the replace() method.

Syntax

public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException

Example

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();
   }
}

Output

Updated on: 12-Feb-2020

266 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements