public class AutoCompleteTextField
ImplementsActionSource, Animation, Editable, StyleListener, TextHolder
An editable com.codename1.ui.TextField with completion suggestions
that show up in a drop down menu while the user types in text.
This class uses the “TextField” UIID by default as well as “AutoCompletePopup” &
“AutoCompleteList” for the popup list details.
The sample below shows the more trivial use case for this widget:
Form hi = new Form("Auto Complete", new BoxLayout(BoxLayout.Y_AXIS));
AutoCompleteTextField ac = new AutoCompleteTextField("Short", "Shock", "Sholder", "Shrek");
ac.setMinimumElementsShownInPopup(5);
hi.add(ac);
The following sample shows more dynamic usage of the class where the auto-complete model is mutated based on webservice results.
public void showForm() {
final DefaultListModel options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
@Override
protected boolean filter(String text) {
if(text.length() == 0) {
return false;
}
String[] l = searchLocations(text);
if(l == null || l.length == 0) {
return false;
}
options.removeAll();
for(String s : l) {
options.addItem(s);
}
return true;
}
};
ac.setMinimumElementsShownInPopup(5);
hi.add(ac);
hi.add(new SpanLabel("This demo requires a valid google API key to be set below "
+ "you can get this key for the webservice (not the native key) by following the instructions here: "
+ "https://developers.google.com/places/web-service/get-api-key"));
hi.add(apiKey);
hi.getToolbar().addCommandToRightBar("Get Key", null, e -> Display.getInstance().execute("https://developers.google.com/places/web-service/get-api-key"));
hi.show();
}
TextField apiKey = new TextField();
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json");
r.addArgument("key", apiKey.getText());
r.addArgument("input", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
String[] res = Result.fromContent(result).getAsStringArray("//description");
return res;
}
} catch(Exception err) {
Log.e(err);
}
return null;
}
Fields
public static final int POPUP_POSITION_AUTO = 0 | |
public static final int POPUP_POSITION_OVER = 1 | |
public static final int POPUP_POSITION_UNDER = 2 |
Constructors
public AutoCompleteTextField(String... completion) | Constructor with completion suggestions |
public AutoCompleteTextField(ListModel<String> listModel) | Constructor with completion suggestions, filtering is automatic in this case |
public AutoCompleteTextField() | The default constructor is useful for cases of filter subclasses overriding the getSuggestionModel value as well as for the GUI builder |
Methods
protected void initComponent() | Allows subclasses to bind functionality that relies on fully initialized and “ready for action” component state |
protected void deinitialize() | Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy. |
public void showPopup() | Causes the popup UI to show |
public void setText(String text) | Sets the text within this text area |
protected void updateFilterList() | In a case of an asynchronous filter this method can be invoked to refresh the completion list |
protected boolean filter(String text) | Subclasses can override this method to perform more elaborate filter operations |
protected ListModel<String> getSuggestionModel() | Returns the list model to show within the completion list |
public void setCompletionRenderer(ListCellRenderer completionRenderer) | Sets a custom renderer to the completion suggestions list. |
public void keyPressed(int k) | If this Component is focused, the key pressed event will call this method |
public void keyReleased(int k) | If this Component is focused, the key released event will call this method |
public void addListListener(ActionListener a) | Adds an action listener that fires an event when an entry in the auto-complete list is selected. |
public void removeListListener(ActionListener a) | Removes an action listener that fires an event when an entry in the auto-complete list is selected. |
public int getMinimumLength() | Indicates the minimum length of text in the field in order for a popup to show the default is 0 where a popup is shown immediately for all text length if the number is 2 a popup will only appear when there are two characters or more. |
public void setMinimumLength(int minimumLength) | Indicates the minimum length of text in the field in order for a popup to show the default is 0 where a popup is shown immediately for all text length if the number is 2 a popup will only appear when there are two characters or more. |
public int getMinimumElementsShownInPopup() | The number of elements shown for the auto complete popup |
public void setMinimumElementsShownInPopup(int minimumElementsShownInPopup) | The number of elements shown for the auto complete popup |
public void setPopupPosition(int popupPosition) | Set the autocomplete popup position in respect of the text field; POPUP_POSITION_AUTO is the default and it means that the popup is placed according to the available space. |
protected boolean shouldShowPopup() | Callback that allows subclasses to block the popup from showing |
public String[] getPropertyNames() | A component may expose mutable property names for a UI designer to manipulate, this API is designed for usage internally by the GUI builder code |
public Class[] getPropertyTypes() | Matches the property names method (see that method for further details). |
public String[] getPropertyTypeNames() | This method is here to workaround an XMLVM array type bug where property types aren’t identified properly, it returns the names of the types using the following type names: String,int,double,long,byte,short,char,String[],String[][],byte[],I… |
public Object getPropertyValue(String name) | Returns the current value of the property name, this method is used by the GUI builder |
public String[] getCompletion() | Returns the completion values |
public void setCompletion(String... completion) | Sets the completion values |
public String setPropertyValue(String name, Object value) | Sets a new value to the given property, returns an error message if failed and null if successful. |
public boolean isStartsWithMode() | When enabled this makes the filter check that the string starts with rather than within the index |
public void setStartsWithMode(boolean startsWithMode) | When enabled this makes the filter check that the string starts with rather than within the index |
Inherited fields
From TextArea
ANY, EMAILADDR, NUMERIC, PHONENUMBER, URL, DECIMAL, PASSWORD, UNEDITABLE, SENSITIVE, NON_PREDICTIVE, INITIAL_CAPS_WORD, INITIAL_CAPS_SENTENCE, USERNAME, UPPERCASE, ONE_TIME_CODE
From Component
DEFAULT_CURSOR, CROSSHAIR_CURSOR, TEXT_CURSOR, WAIT_CURSOR, SW_RESIZE_CURSOR, SE_RESIZE_CURSOR, NW_RESIZE_CURSOR, NE_RESIZE_CURSOR, N_RESIZE_CURSOR, S_RESIZE_CURSOR, W_RESIZE_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, MOVE_CURSOR, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_Y, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_IMMEDIATELY_DRAG_XY, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_CENTER_OFFSET, BRB_OTHER, CENTER, TOP, LEFT, BOTTOM, RIGHT, BASELINE
Inherited methods
From TextField
isUseNativeTextInput, setUseNativeTextInput, setClearText, setT9Text, create, create, create, create, addInputMode, getDefaultInputModeOrder, setDefaultInputModeOrder, getSymbolTable, setSymbolTable, isReplaceMenuDefault, setReplaceMenuDefault, isQwertyAutoDetect, setQwertyAutoDetect, isQwertyDevice, setQwertyDevice, getDefaultChangeInputModeKey, setDefaultChangeInputModeKey, getDefaultSymbolDialogKey, setDefaultSymbolDialogKey, isEnableInputScroll, setEnableInputScroll, deleteChar, commitChange, isPendingCommit, getCommitTimeout, setCommitTimeout, getInputMode, setInputMode, isChangeInputMode, getInputModeOrder, setInputModeOrder, getLongClickInputMode, getCharPerKeyCode, getCursorPosition, setCursorPosition, getCursorY, getCursorX, clear, isClearKey, longKeyPress, isQwertyInput, setQwertyInput, isImmediateInputMode, insertChars, validChar, showSymbolDialog, createSymbolTable, getLongClickDuration, isCursorPositionCycle, isSymbolDialogKey, setEditable, keyRepeated, installCommands, isSelectableInteraction, fireClicked, removeCommands, isEditingTrigger, isEditingEndTrigger, paint, calcPreferredSize, getCursorBlinkTimeOn, setCursorBlinkTimeOn, getCursorBlinkTimeOff, setCursorBlinkTimeOff, animate, pointerReleased, isUseSoftkeys, setUseSoftkeys, isReplaceMenu, setReplaceMenu, isOverwriteMode, setOverwriteMode, isLeftAndRightEditingTrigger, setLeftAndRightEditingTrigger, calculateTextSelectionSpan
From TextArea
getDefaultValign, setDefaultValign, setDefaultMaxSize, isAutoDegradeMaxSize, setAutoDegradeMaxSize, getWidestChar, setWidestChar, autoDetectWidestChar, isUseStringWidth, setUseStringWidth, initLaf, getConstraint, setConstraint, setWidth, getText, getAsInt, getAsLong, getAsDouble, isEditable, getPreferredTabIndex, getMaxSize, setMaxSize, isScrollableY, pointerHover, pointerHoverReleased, getColumns, setColumns, getActualRows, getRows, setRows, getLines, getTextAt, preprocess, getRowsGap, setRowsGap, calcScrollSize, addActionListener, removeActionListener, addCloseListener, removeCloseListener, isGrowByContent, setGrowByContent, getUnsupportedChars, setUnsupportedChars, getLinesToScroll, setLinesToScroll, isSingleLineTextArea, setSingleLineTextArea, getAlignment, setAlignment, getAbsoluteAlignment, isEnterKey, getHint, setHint, getHintIcon, setHintIcon, setHint, getHintLabel, getVerticalAlignment, setVerticalAlignment, getBindablePropertyNames, getBindablePropertyTypes, bindProperty, unbindProperty, getBoundPropertyValue, setBoundPropertyValue, getGrowLimit, setGrowLimit, isEndsWith3Points, setEndsWith3Points, registerAsInputDevice, startEditing, startEditingAsync, isEditing, stopEditing, stopEditing, getStyle, addDataChangedListener, removeDataChangedListener, addDataChangeListener, removeDataChangeListener, fireDataChanged, getDoneListener, setDoneListener, fireDoneEvent, fireDoneEvent, isActAsLabel, setActAsLabel, shouldRenderComponentSelection, isTextSelectionEnabled, setTextSelectionEnabled, getTextSelectionSupport
From Component
setSameSize, isSetCursorSupported, parsePreferredSize, getDefaultDragTransparency, setDefaultDragTransparency, getEditingDelegate, setEditingDelegate, getCursor, setCursor, showNativeOverlay, hideNativeOverlay, updateNativeOverlay, getNativeOverlay, getAllStyles, getSameWidth, setSameWidth, getSameHeight, setSameHeight, getUIManager, getX, setX, getOuterX, getInnerX, getY, setY, getOuterY, getInnerY, isVisible, setVisible, getClientProperty, stripMarginAndPadding, clearClientProperties, putClientProperty, getDirtyRegion, setDirtyRegion, isOpaque, setOpaque, getWidth, getOuterWidth, getInnerWidth, getHeight, setHeight, getOuterHeight, getInnerHeight, isDragRegion, getDragRegionStatus, getBaseline, getBaselineResizeBehavior, getPreferredSizeStr, setPreferredSizeStr, getPreferredSize, setPreferredSize, getScrollDimension, setScrollSize, getPreferredW, setPreferredW, getPreferredH, setPreferredH, getOuterPreferredH, getInnerPreferredH, getOuterPreferredW, getInnerPreferredW, setSize, getUIID, setUIID, setUIIDFinal, setUIID, getInlineAllStyles, setInlineAllStyles, getInlineSelectedStyles, setInlineSelectedStyles, getInlineUnselectedStyles, setInlineUnselectedStyles, getInlineDisabledStyles, setInlineDisabledStyles, getInlinePressedStyles, setInlinePressedStyles, remove, getParent, getOwner, setOwner, isOwnedBy, containsOrOwns, addFocusListener, removeFocusListener, addScrollListener, removeScrollListener, getSelectCommandText, setSelectCommandText, getLabelForComponent, setLabelForComponent, focusGained, focusLost, paintBackgrounds, paintShadows, getAbsoluteX, getAbsoluteY, isInClippingRegion, paintIntersectingComponentsAbove, paintScrollbars, paintScrollbarX, getScrollOpacity, getSelectedRect, paintScrollbarY, paintComponent, paintComponent, getBorder, getScrollable, paintBackground, isScrollable, isScrollableX, getScrollX, setScrollX, getScrollY, setScrollY, onScrollX, onScrollY, getDraggedx, getDraggedy, getBottomGap, getSideGap, contains, visibleBoundsContains, hasFixedPreferredSize, getBounds, getBounds, getVisibleBounds, getVisibleBounds, isFocusable, setFocusable, onSetFocusable, resetFocusable, getTabIndex, setTabIndex, setPreferredTabIndex, isTraversable, setTraversable, setShouldCalcPreferredSize, handlesInput, setHandlesInput, consumesRawTextInput, hasFocus, setFocus, getComponentForm, getTopLevelContainer, repaint, repaint, registerForAnimation, deregisterFromAnimation, getAnimationManager, getScrollAnimationSpeed, setScrollAnimationSpeed, isBlockLead, setBlockLead, isIgnorePointerEvents, setIgnorePointerEvents, isRippleEffect, setRippleEffect, getInlineStylesTheme, setInlineStylesTheme, isHideInLandscape, setHideInLandscape, createStyleAnimation, isSmoothScrolling, setSmoothScrolling, stopScrollMomentum, pointerHoverPressed, pinch, pinchReleased, pinch, rotation, isPinchBlocksDragAndDrop, setPinchBlocksDragAndDrop, pointerDragged, getDragImage, getDragTransparency, setDragTransparency, toImage, dragInitiated, drawDraggedImage, draggingOver, dragEnter, dragExit, drop, addPullToRefresh, setPullToRefresh, respondsToPointerEvents, pointerDragged, isStickyDrag, pointerPressed, isDragAndDropOperation, pointerPressed, pointerReleased, longPointerPress, setVerticalScrollBounds, setHorizontalScrollBounds, isVScrollThumbGrabbed, isHScrollThumbGrabbed, isVScrollThumbHover, isHScrollThumbHover, isTensileDragEnabled, setTensileDragEnabled, addDropListener, removeDropListener, addDragOverListener, removeDragOverListener, isNativeDragSource, setNativeDragSource, getNativeDragOperation, setNativeDragOperation, createNativeDragOperation, isNativeDropTarget, setNativeDropTarget, getAcceptedDropMimeTypes, setAcceptedDropMimeTypes, getAcceptedDropActions, setAcceptedDropActions, canAcceptNativeDrop, nativeDragEnter, nativeDragOver, nativeDragExit, nativeDrop, addNativeDropListener, removeNativeDropListener, addNativeDragOverListener, removeNativeDragOverListener, dragFinished, addDragFinishedListener, addStateChangeListener, removeStateChangeListener, addPointerPressedListener, addLongPressListener, addContextMenuListener, removeContextMenuListener, addMouseWheelListener, removeMouseWheelListener, addStylusListener, removeStylusListener, mouseWheel, paintRippleOverlay, removePointerPressedListener, removeLongPressListener, removeDragFinishedListener, addPointerReleasedListener, removePointerReleasedListener, addPointerDraggedListener, removePointerDraggedListener, getDragSpeed, getPressedStyle, setPressedStyle, initUnselectedStyle, initPressedStyle, initDisabledStyle, initSelectedStyle, getUnselectedStyle, setUnselectedStyle, getSelectedStyle, setSelectedStyle, getDisabledStyle, setDisabledStyle, installDefaultPainter, requestFocus, toString, paramString, refreshTheme, refreshTheme, refreshTheme, isDragActivated, getGridPosY, getGridPosX, scrollRectToVisible, scrollRectToVisible, paintBorder, paintBorderBackground, isCellRenderer, setCellRenderer, isScrollVisible, setScrollVisible, setIsScrollVisible, laidOut, isInitialized, setInitialized, styleChanged, getNextFocusDown, setNextFocusDown, getNextFocusUp, setNextFocusUp, getNextFocusLeft, setNextFocusLeft, getNextFocusRight, setNextFocusRight, isEnabled, setEnabled, getName, setName, initCustomStyle, deinitializeCustomStyle, isRTL, setRTL, isTactileTouch, isTactileTouch, setTactileTouch, paintLockRelease, paintLock, isSnapToGrid, setSnapToGrid, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, blocksSideSwipe, isFlatten, setFlatten, getTensileLength, setTensileLength, isGrabsPointerEvents, setGrabsPointerEvents, getScrollOpacityChangeSpeed, setScrollOpacityChangeSpeed, growShrink, isAlwaysTensile, setAlwaysTensile, isDraggable, setDraggable, isDropTarget, setDropTarget, isChildOf, isHideInPortrait, setHideInPortrait, cancelRepaints, getCloudBoundProperty, setCloudBoundProperty, getCloudDestinationProperty, setCloudDestinationProperty, getComponentState, setComponentState, setHidden, isHidden, setHidden, isHidden, announceForAccessibility, getAccessibilityText, setAccessibilityText, getSemantics, getAccessibilityNode, accessibilityChanged, accessibilityChanged, getTooltip, setTooltip
Field details
POPUP_POSITION_AUTO
public static final int POPUP_POSITION_AUTO = 0POPUP_POSITION_OVER
public static final int POPUP_POSITION_OVER = 1POPUP_POSITION_UNDER
public static final int POPUP_POSITION_UNDER = 2Constructor details
AutoCompleteTextField
public AutoCompleteTextField(String... completion)Parameters
completionString...- a String array of suggestion for completion
AutoCompleteTextField
public AutoCompleteTextField(ListModel<String> listModel)Parameters
listModelListModel<String>- a list model containing potential string suggestions
AutoCompleteTextField
public AutoCompleteTextField()Method details
initComponent
protected void initComponent()deinitialize
protected void deinitialize()showPopup
public void showPopup()setText
public void setText(String text)Parameters
textString- new value for the text area
updateFilterList
protected void updateFilterList()filter
protected boolean filter(String text)Parameters
textString- the text to filter
Returns
getSuggestionModel
protected ListModel<String> getSuggestionModel()Returns
setCompletionRenderer
public void setCompletionRenderer(ListCellRenderer completionRenderer)Parameters
completionRendererListCellRenderer- a ListCellRenderer for the suggestions List
keyPressed
public void keyPressed(int k)Parameters
kint- the key code value to indicate a physical key.
keyReleased
public void keyReleased(int k)Parameters
kint- the key code value to indicate a physical key.
addListListener
public void addListListener(ActionListener a)Parameters
aActionListener- the listener
removeListListener
public void removeListListener(ActionListener a)Parameters
aActionListener- the listener
getMinimumLength
public int getMinimumLength()Returns
setMinimumLength
public void setMinimumLength(int minimumLength)Parameters
minimumLengthint- the minimumLength to set
getMinimumElementsShownInPopup
public int getMinimumElementsShownInPopup()Returns
setMinimumElementsShownInPopup
public void setMinimumElementsShownInPopup(int minimumElementsShownInPopup)Parameters
minimumElementsShownInPopupint- the minimumElementsShownInPopup to set
setPopupPosition
public void setPopupPosition(int popupPosition)Parameters
popupPositionint- on of POPUP_POSITION_AUTO, POPUP_POSITION_OVER, POPUP_POSITION_UNDER
shouldShowPopup
protected boolean shouldShowPopup()Returns
getPropertyNames
public String[] getPropertyNames()Returns
getPropertyTypes
public Class[] getPropertyTypes()Returns
getPropertyTypeNames
public String[] getPropertyTypeNames()Returns
getPropertyValue
public Object getPropertyValue(String name)Parameters
nameString- the name of the property
Returns
getCompletion
public String[] getCompletion()Returns
setCompletion
public void setCompletion(String... completion)Parameters
completionString...- the completion values
setPropertyValue
public String setPropertyValue(String name, Object value)Parameters
nameString- the name of the property
valueObject- new value for the property
Returns
isStartsWithMode
public boolean isStartsWithMode()Returns
setStartsWithMode
public void setStartsWithMode(boolean startsWithMode)Parameters
startsWithModeboolean- the startsWithMode to set