Class OtpField

All Implemented Interfaces:
Animation, Editable, StyleListener, Iterable<Component>

public class OtpField extends Container

Segmented one-time-password input -- one box per digit, auto-advances to the next box on input and steps back on backspace. Standard pattern for SMS / authenticator code entry screens.

Example
OtpField otp = new OtpField(6);
otp.addCompleteListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        String code = otp.getText();
        // verify code...
    }
});
form.add(otp);

Style the individual boxes with the UIID "OtpDigit"; the field itself uses "OtpField".

  • Constructor Details

    • OtpField

      public OtpField()
      Builds a 6-digit numeric OTP field -- the common case.
    • OtpField

      public OtpField(int length)

      Builds an OTP field of the given length, numeric only.

      Parameters
      • length: number of digits / characters (e.g. 4, 6, 8)
    • OtpField

      public OtpField(int length, boolean numericOnly)

      Full constructor.

      Parameters
      • length: number of digits / characters

      • numericOnly: true to restrict input to digits; false to allow any character (alphanumeric OTP codes are sometimes used)

  • Method Details

    • getText

      public String getText()
      Returns the current value, in order from the first box to the last. Empty boxes are omitted, so a partial entry returns a shorter string.
    • setText

      public void setText(String code)
      Sets the value, distributing one character per box. Excess characters are silently dropped; shorter strings leave the remaining boxes empty.
    • clear

      public void clear()
      Clears all boxes.
    • addCompleteListener

      public void addCompleteListener(ActionListener l)
      Adds a listener fired when the field becomes completely filled. Useful to trigger automatic verification.
    • removeCompleteListener

      public void removeCompleteListener(ActionListener l)
      Removes a previously-registered listener.
    • getBox

      public TextField getBox(int index)
      Returns the underlying TextField for the box at index. Useful for custom theming / focus management.
    • getLength

      public int getLength()
      Returns the configured length (number of boxes).