# Class OtpField

java.lang.Object
com.codename1.ui.Component
com.codename1.ui.Container
com.codename1.components.OtpField

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

public class OtpField extends Container

Segmented one-time-code input -- one box per digit, with a caret that walks from box to box as the code is typed. The standard entry screen for an SMS or authenticator code, and the second half of phone number verification.

##### Example

    OtpField otp = new OtpField(6);
    otp.addCompleteListener(e -> verify(otp.getText()));
    form.add(otp);

##### Receiving the code from the SMS

The field carries `TextArea#ONE_TIME_CODE`, so the platform offers the code from the incoming message by itself: on iOS the keyboard's suggestion bar shows it above the keys, on Android the autofill service offers it on the field. Accepting it fills every box at once. The application reads no messages and asks for no messaging permission -- it only says what the field is for, and the platform does the rest. A platform that cannot offer the code is unaffected, and the code is typed.

This is why the boxes are drawn rather than being separate editors. A code arrives as one value, and a row of one-character fields can only receive one character of it. Behind the boxes is a single field holding the whole code, so an offered code, a paste and a keyboard all land the same way.

##### Styling

Each box uses the UIID "OtpDigit" and the field itself uses "OtpField".

- ## Field Summary

  ### Fields inherited from class Component

  `BASELINE, BOTTOM, BRB_CENTER_OFFSET, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_OTHER, CENTER, CROSSHAIR_CURSOR, DEFAULT_CURSOR, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_POSSIBLE_DRAG_Y, E_RESIZE_CURSOR, HAND_CURSOR, LEFT, MOVE_CURSOR, N_RESIZE_CURSOR, NE_RESIZE_CURSOR, NW_RESIZE_CURSOR, RIGHT, S_RESIZE_CURSOR, SE_RESIZE_CURSOR, SW_RESIZE_CURSOR, TEXT_CURSOR, TOP, W_RESIZE_CURSOR, WAIT_CURSOR`

- ## Constructor Summary

  Constructors
  Constructor
  Description
  `OtpField()`
  Builds a 6-digit numeric field -- the common case.
  `OtpField(int length)`
  Builds a field of the given length, numeric only.
  `OtpField(int length, boolean numericOnly)`
  Full constructor.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `void`
  `addCompleteListener(ActionListener l)`
  Adds a listener fired on the edit that fills the last box.
  `void`
  `addDataChangedListener(DataChangedListener l)`
  Adds a listener fired on every change to the value, not only on the one that completes it.
  `void`
  `clear()`
  Clears every box and puts the caret back in the first one, ready for a fresh code.
  `TextField`
  `getBox(int index)`
  Returns the box at `index`, which displays the character at that position.
  `EditField`
  `getInputField()`
  The field that actually holds the code and carries the one-time-code hint.
  `int`
  `getLength()`
  Returns the configured length (number of boxes).
  `String`
  `getText()`
  Returns the current value, in order from the first box to the last.
  `boolean`
  `isComplete()`
  True when every box holds a character.
  `boolean`
  `isNumericOnly()`
  True when the field accepts digits only.
  `void`
  `removeCompleteListener(ActionListener l)`
  Removes a previously-registered listener.
  `void`
  `removeDataChangedListener(DataChangedListener l)`
  Removes a previously-registered listener.
  `void`
  `setText(String code)`
  Sets the value, one character per box.
  `void`
  `startEditing()`
  Focuses the field and opens the keyboard, so a verification screen can put the user straight into the code without a tap.

  ### Methods inherited from class Container

  `add, add, add, add, add, add, addAll, addComponent, addComponent, addComponent, addComponent, animateHierarchy, animateHierarchyAndWait, animateHierarchyFade, animateHierarchyFadeAndWait, animateLayout, animateLayoutAndWait, animateLayoutFade, animateLayoutFadeAndWait, animateUnlayout, animateUnlayoutAndWait, applyRTL, calcPreferredSize, cancelRepaints, clearClientProperties, constrainHeightWhenScrollable, constrainWidthWhenScrollable, contains, createAnimateHierarchy, createAnimateHierarchyFade, createAnimateLayout, createAnimateLayoutFade, createAnimateLayoutFadeAndWait, createAnimateMotion, createAnimateUnlayout, createReplaceTransition, dragInitiated, drop, encloseIn, encloseIn, findDropTargetAt, findFirstFocusable, fireClicked, flushReplace, forceRevalidate, getBottomGap, getChildrenAsList, getClosestComponentTo, getComponentAt, getComponentAt, getComponentCount, getComponentIndex, getGridPosX, getGridPosY, getLayout, getLayoutHeight, getLayoutWidth, getLeadComponent, getLeadParent, getResponderAt, getSafeAreaRoot, getScrollIncrement, getSideGap, getUIManager, initLaf, invalidate, isEnabled, isSafeArea, isSafeAreaRoot, isScrollableX, isScrollableY, isSelectableInteraction, isSurface, iterator, iterator, keyPressed, keyReleased, layoutContainer, morph, morphAndWait, paint, paintComponentBackground, paintGlass, paramString, pointerPressed, refreshTheme, removeAll, removeComponent, replace, replace, replaceAndWait, replaceAndWait, replaceAndWait, revalidate, revalidateLater, revalidateWithAnimationSafety, scrollComponentToVisible, setCellRenderer, setEnabled, setLayout, setLeadComponent, setSafeArea, setSafeAreaRoot, setScrollable, setScrollableX, setScrollableY, setScrollIncrement, setShouldCalcPreferredSize, setShouldLayout, setUIManager, updateTabIndices`

  ### Methods inherited from class Component

  `accessibilityChanged, accessibilityChanged, addContextMenuListener, addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addMouseWheelListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, addStylusListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, consumesRawTextInput, contains, containsOrOwns, createStyleAnimation, deinitialize, deinitializeCustomStyle, deregisterFromAnimation, dragEnter, dragExit, dragFinished, draggingOver, drawDraggedImage, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAccessibilityNode, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getHeight, getInlineAllStyles, getInlineDisabledStyles, getInlinePressedStyles, getInlineSelectedStyles, getInlineStylesTheme, getInlineUnselectedStyles, getInnerHeight, getInnerPreferredH, getInnerPreferredW, getInnerWidth, getInnerX, getInnerY, getLabelForComponent, getName, getNativeOverlay, getNextFocusDown, getNextFocusLeft, getNextFocusRight, getNextFocusUp, getOuterHeight, getOuterPreferredH, getOuterPreferredW, getOuterWidth, getOuterX, getOuterY, getOwner, getParent, getPreferredH, getPreferredSize, getPreferredSizeStr, getPreferredTabIndex, getPreferredW, getPressedStyle, getPropertyNames, getPropertyTypeNames, getPropertyTypes, getPropertyValue, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getSemantics, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getTopLevelContainer, getUIID, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, handlesInput, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initComponent, initCustomStyle, initDisabledStyle, initPressedStyle, initSelectedStyle, initUnselectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isHScrollThumbGrabbed, isHScrollThumbHover, isIgnorePointerEvents, isInClippingRegion, isInitialized, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollVisible, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isStickyDrag, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, isVScrollThumbGrabbed, isVScrollThumbHover, keyRepeated, laidOut, longKeyPress, longPointerPress, mouseWheel, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerReleased, pointerReleased, putClientProperty, refreshTheme, refreshTheme, registerForAnimation, remove, removeContextMenuListener, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removeMouseWheelListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, removeStylusListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, rotation, scrollRectToVisible, scrollRectToVisible, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setHorizontalScrollBounds, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNextFocusDown, setNextFocusLeft, setNextFocusRight, setNextFocusUp, setOpaque, setOwner, setPinchBlocksDragAndDrop, setPreferredH, setPreferredSize, setPreferredSizeStr, setPreferredTabIndex, setPreferredW, setPressedStyle, setPropertyValue, setPullToRefresh, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setSize, setSmoothScrolling, setSnapToGrid, setTabIndex, setTactileTouch, setTensileDragEnabled, setTensileLength, setTooltip, setTraversable, setUIID, setUIID, setUIIDFinal, setUnselectedStyle, setVerticalScrollBounds, setVisible, setWidth, setX, setY, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stripMarginAndPadding, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains`

  ### Methods inherited from class Object

  `clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait`

  ### Methods inherited from interface Iterable

  `forEach`

- ## Constructor Details

  - ### OtpField

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

  - ### OtpField

    public OtpField(int length)

    Builds a 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 codes are sometimes used)

- ## Method Details

  - ### getText

    public String getText()
    Returns the current value, in order from the first box to the last. A partial entry returns a shorter string.

  - ### setText

    public void setText(String code)

    Sets the value, one character per box. Excess characters are dropped, as are characters this field does not accept; a shorter string leaves the remaining boxes empty.

    ###### Parameters

    - `code`: the value, or null to clear

  - ### clear

    public void clear()
    Clears every box and puts the caret back in the first one, ready for a fresh code.

  - ### startEditing

    public void startEditing()
    Focuses the field and opens the keyboard, so a verification screen can put the user straight into the code without a tap.

  - ### isComplete

    public boolean isComplete()
    True when every box holds a character.

  - ### addCompleteListener

    public void addCompleteListener(ActionListener l)

    Adds a listener fired on the edit that fills the last box. Useful to verify the code without a submit button.

    ###### Parameters

    - `l`: the listener

  - ### removeCompleteListener

    public void removeCompleteListener(ActionListener l)

    Removes a previously-registered listener.

    ###### Parameters

    - `l`: the listener

  - ### addDataChangedListener

    public void addDataChangedListener(DataChangedListener l)

    Adds a listener fired on every change to the value, not only on the one that completes it.

    ###### Parameters

    - `l`: the listener

  - ### removeDataChangedListener

    public void removeDataChangedListener(DataChangedListener l)

    Removes a previously-registered listener.

    ###### Parameters

    - `l`: the listener

  - ### getBox

    public TextField getBox(int index)

    Returns the box at `index`, which displays the character at that position. Useful for theming an individual box; the value itself is read and written through `#getText()` / `#setText(String)`, since a code is entered into the field as a whole rather than box by box.

    ###### Parameters

    - `index`: the box position, from 0

    ###### Returns

    the box at that position

  - ### getInputField

    public EditField getInputField()
    The field that actually holds the code and carries the one-time-code hint. It spans the boxes and draws only the caret. Exposed for the cases the boxes cannot serve: adding a done listener, or reading the caret.

  - ### getLength

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

  - ### isNumericOnly

    public boolean isNumericOnly()
    True when the field accepts digits only.