Class Slider
- All Implemented Interfaces:
Animation, Editable, ActionSource, StyleListener, IconHolder, TextHolder
- Direct Known Subclasses:
SliderBridge
The slider component serves both as a slider widget to allow users to select a value on a scale via touch/arrows and also to indicate progress. The slider defaults to percentage display but can represent any positive set of values.
Slider is very versatile and can be used to represent things as diverse as the 5 star ranking UI
demonstrated below. Notice that for the UI to work correctly you need to enclose it in a layout that preserves
its preferred size like flow layout.
public void showForm() {
Form hi = new Form("Star Slider", new BoxLayout(BoxLayout.Y_AXIS));
hi.add(FlowLayout.encloseCenter(createStarRankSlider()));
hi.show();
}
private void initStarRankStyle(Style s, Image star) {
s.setBackgroundType(Style.BACKGROUND_IMAGE_TILE_BOTH);
s.setBorder(Border.createEmpty());
s.setBgImage(star);
s.setBgTransparency(0);
}
private Slider createStarRankSlider() {
Slider starRank = new Slider();
starRank.setEditable(true);
starRank.setMinValue(0);
starRank.setMaxValue(10);
Font fnt = Font.createTrueTypeFont("native:mainLight", "native:mainLight").
derive(Display.getInstance().convertToPixels(5, true), Font.STYLE_PLAIN);
Style s = new Style(0xffff33, 0, fnt, (byte)0);
Image fullStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
s.setOpacity(100);
s.setFgColor(0);
Image emptyStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
initStarRankStyle(starRank.getSliderEmptySelectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderEmptyUnselectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderFullSelectedStyle(), fullStar);
initStarRankStyle(starRank.getSliderFullUnselectedStyle(), fullStar);
starRank.setPreferredSize(new Dimension(fullStar.getWidth() * 5, fullStar.getHeight()));
return starRank;
}
Slider can be used as a progress indicator for network operations when combined with the
com.codename1.components.SliderBridge component:
Form hi = new Form("Download Progress", new BorderLayout());
Slider progress = new Slider();
Button download = new Button("Download");
download.addActionListener((e) -> {
ConnectionRequest cr = new ConnectionRequest("https://www.codenameone.com/img/blog/new_icon.png", false);
SliderBridge.bindProgress(cr, progress);
NetworkManager.getInstance().addToQueueAndWait(cr);
if(cr.getResponseCode() == 200) {
hi.add(BorderLayout.CENTER, new ScaleImageLabel(EncodedImage.create(cr.getResponseData())));
hi.revalidate();
}
});
hi.add(BorderLayout.SOUTH, progress).add(BorderLayout.NORTH, download);
hi.show();
-
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 -
Method Summary
Modifier and TypeMethodDescriptionvoidAction listeners give a more coarse event only when the user lifts the finger from the slidervoidAdds a listener to data changed events, notice that the status argument to the data change listener shouldn't be relied upon.booleananimate()Allows the animation to reduce "repaint" calls when it returns false.protected DimensionReturn the size we would generally like for the componentstatic SliderCreates an infinite progress slidervoidInvoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.protected voidWhen working in 3 softbutton mode "fire" key (center softbutton) is sent to this method in order to allow 3 button devices to work properly.protected StringformattedValue(int value) Allows formatting the appearance of the progress when text is drawn on topintThe increments when the user presses a key to the left/right/up/down etc.intReturns
intReturns
intIndicates the value of progress madeintgetProgress(ActionEvent evt) Gets the progress of the slider at the point where the provided ActionEvent was triggered.Returns thecom.codename1.ui.plaf.Styleused to paint the slider when its full and selectedReturns thecom.codename1.ui.plaf.Styleused to paint the slider when its fullReturns thecom.codename1.ui.plaf.Styleused to paint the slider when its full and selectedReturns thecom.codename1.ui.plaf.Styleused to paint the slider when its fullgetStyle()Returns the current Component Style allowing code to draw the current component, you should normally use getUnselected/Pressed/DisabledStyle() and not this method since it will return different values based on component state.The thumb image is drawn on top of the current progressvoidAllows subclasses to bind functionality that relies on fully initialized and "ready for action" component statebooleanIndicates the slider is modifyablebooleanThe infinite slider functionality is used to animate progress for which there is no defined value.booleanIndicates that the value of the slider should be rendered with a percentage sign on top of the slider.booleanReturns
protected booleanThis method allows a component to indicate that it is interested in an "implicit" select command to appear in the "fire" button when 3 softbuttons are defined in a device.protected booleanReturns true if the component is interested in receiving drag/pointer release events even after the gesture exceeded its boundaries.booleanIndicates the slider is verticalvoidkeyPressed(int code) If this Component is focused, the key pressed event will call this methodvoidkeyReleased(int code) If this Component is focused, the key released event will call this methodvoidPaint the progress indicatorvoidpointerDragged(int x, int y) If this Component is focused, the pointer dragged event will call this methodvoidpointerPressed(int x, int y) If this Component is focused, the pointer pressed event will call this methodvoidpointerReleased(int x, int y) If this Component is focused, the pointer released event will call this methodvoidrefreshTheme(boolean merge) Makes sure the component is up to date with the current theme, ONLY INVOKE THIS METHOD IF YOU CHANGED THE THEME!voidAction listeners give a more coarse event only when the user lifts the finger from the slidervoidRemoves a listener from data changed events, notice that the status argument to the data change listener shouldn't be relied upon.voidsetEditable(boolean editable) Indicates the slider is modifyablevoidsetIncrements(int increments) The increments when the user presses a key to the left/right/up/down etc.voidsetInfinite(boolean i) Activates/disables the infinite slider functionality used to animate progress for which there is no defined value.voidsetMaxValue(int maxValue) Parameters
voidsetMinValue(int minValue) Parameters
voidsetProgress(int value) Indicates the value of progress made, this method is thread safe and can be invoked from any thread although discretion should still be kept so one thread doesn't regress progress made by another thread...voidsetRenderPercentageOnTop(boolean renderPercentageOnTop) Indicates that the value of the slider should be rendered with a percentage sign on top of the slider.voidsetRenderValueOnTop(boolean renderValueOnTop) Parameters
voidsetThumbImage(Image thumbImage) The thumb image is drawn on top of the current progressfinal voidThis method sets the Component the Unique identifier.voidsetVertical(boolean vertical) Indicates the slider is verticalprotected booleanA component that might need side swipe such as the slider could block it from being used for some other purpose when on top of said component.Methods inherited from class Label
bindProperty, getAlignment, getBadgeStyleComponent, getBadgeText, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBoundPropertyValue, getDefaultGap, getFontIcon, getFontIconSize, getGap, getIcon, getIconFont, getIconStyleComponent, getIconUIID, getMask, getMaskedIcon, getMaskName, getMaterialIcon, getMaterialIconSize, getMaxAutoSize, getMinAutoSize, getPropertyNames, getPropertyTypeNames, getPropertyTypes, getPropertyValue, getShiftMillimeters, getShiftMillimetersF, getShiftText, getStringWidth, getText, getTextPosition, getTextSelectionSupport, getVerticalAlignment, initLaf, initUnselectedStyle, isAutoSizeMode, isDefaultTickerEnabled, isEndsWith3Points, isLegacyRenderer, isShouldLocalize, isShowEvenIfBlank, isTextSelectionEnabled, isTickerEnabled, isTickerRunning, laidOut, paint, paramString, setAlignment, setAutoSizeMode, setBadgeText, setBadgeUIID, setBoundPropertyValue, setDefaultGap, setDefaultTickerEnabled, setEndsWith3Points, setFontIcon, setFontIcon, setFontIcon, setGap, setIcon, setIconUIID, setLegacyRenderer, setMask, setMaskName, setMaterialIcon, setMaterialIcon, setMaxAutoSize, setMinAutoSize, setPropertyValue, setShiftMillimeters, setShiftMillimeters, setShiftText, setShouldLocalize, setShowEvenIfBlank, setText, setTextPosition, setTextSelectionEnabled, setTickerEnabled, setVerticalAlignment, shouldTickerStart, startTicker, startTicker, stopTicker, styleChanged, unbindPropertyMethods inherited from class Component
addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, announceForAccessibility, blocksSideSwipe, calcScrollSize, cancelRepaints, clearClientProperties, contains, containsOrOwns, createStyleAnimation, deinitializeCustomStyle, dragEnter, dragExit, dragFinished, draggingOver, dragInitiated, drawDraggedImage, drop, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAccessibilityText, getAllStyles, getAnimationManager, getBorder, getBottomGap, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getComponentState, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, getDragRegionStatus, getDragSpeed, getDragTransparency, getEditingDelegate, getGridPosX, getGridPosY, 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, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getSideGap, getTabIndex, getTensileLength, getTooltip, getUIID, getUIManager, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, handlesInput, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initCustomStyle, initDisabledStyle, initPressedStyle, initSelectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditing, isEnabled, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isIgnorePointerEvents, isInClippingRegion, isInitialized, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollableX, isScrollableY, isScrollVisible, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, keyRepeated, longKeyPress, longPointerPress, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerReleased, putClientProperty, refreshTheme, refreshTheme, remove, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, scrollRectToVisible, scrollRectToVisible, setAccessibilityText, setAlwaysTensile, setBlockLead, setCellRenderer, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setEnabled, setFlatten, setFocus, setFocusable, setGrabsPointerEvents, setHandlesInput, setHeight, setHidden, setHidden, setHideInLandscape, setHideInPortrait, setIgnorePointerEvents, setInitialized, setInlineAllStyles, setInlineDisabledStyles, setInlinePressedStyles, setInlineSelectedStyles, setInlineStylesTheme, setInlineUnselectedStyles, setIsScrollVisible, setLabelForComponent, setName, setNextFocusDown, setNextFocusLeft, setNextFocusRight, setNextFocusUp, setOpaque, setOwner, setPinchBlocksDragAndDrop, setPreferredH, setPreferredSize, setPreferredSizeStr, setPreferredTabIndex, setPreferredW, setPressedStyle, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setShouldCalcPreferredSize, setSize, setSmoothScrolling, setSnapToGrid, setTabIndex, setTactileTouch, setTensileDragEnabled, setTensileLength, setTooltip, setTraversable, setUIID, setUIIDFinal, setUnselectedStyle, setVisible, setWidth, setX, setY, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, shouldRenderComponentSelection, showNativeOverlay, startEditingAsync, stopEditing, stripMarginAndPadding, toImage, toString, updateNativeOverlay, visibleBoundsContains
-
Constructor Details
-
Slider
public Slider()The default constructor uses internal rendering to draw its state
-
-
Method Details
-
createInfinite
Creates an infinite progress slider
Returns
a slider instance that has no end value
-
setUIID
-
isStickyDrag
protected boolean isStickyDrag()Returns true if the component is interested in receiving drag/pointer release events even after the gesture exceeded its boundaries. This is useful for spinners etc. where the motion might continue beyond the size of the component
Returns
false by default
- Overrides:
isStickyDragin classComponent
-
initComponent
public void initComponent()Allows subclasses to bind functionality that relies on fully initialized and "ready for action" component state- Overrides:
initComponentin classComponent
-
deinitialize
public void deinitialize()Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy. This allows the component to deregister animators and cleanup after itself. This method is the opposite of the initComponent() method.- Overrides:
deinitializein classComponent
-
animate
public boolean animate()Allows the animation to reduce "repaint" calls when it returns false. It is called once for every frame. Frames are defined by the
com.codename1.ui.Displayclass.Returns
true if a repaint is desired or false if no repaint is necessary
-
isInfinite
public boolean isInfinite()The infinite slider functionality is used to animate progress for which there is no defined value.
Returns
true for infinite progress
-
setInfinite
public void setInfinite(boolean i) Activates/disables the infinite slider functionality used to animate progress for which there is no defined value.
Parameters
i: true for infinite progress
-
refreshTheme
public void refreshTheme(boolean merge) Makes sure the component is up to date with the current theme, ONLY INVOKE THIS METHOD IF YOU CHANGED THE THEME!
Parameters
merge: indicates if the current styles should be merged with the new styles
- Overrides:
refreshThemein classLabel
-
getProgress
public int getProgress()Indicates the value of progress made
Returns
the progress on the slider
-
setProgress
public void setProgress(int value) Indicates the value of progress made, this method is thread safe and can be invoked from any thread although discretion should still be kept so one thread doesn't regress progress made by another thread...
Parameters
value: new value for progress
-
getProgress
Gets the progress of the slider at the point where the provided ActionEvent was triggered.
Parameters
evt: An ActionEvent that originated from this slider.
Returns
The progress of the slider.
Since
7.0
-
formattedValue
Allows formatting the appearance of the progress when text is drawn on top
Parameters
value: the value of the slider
Returns
a string formatted version
-
getSliderFullUnselectedStyle
Returns the
com.codename1.ui.plaf.Styleused to paint the slider when its fullReturns
the Style object that shows a completely full style.
-
getSliderFullSelectedStyle
Returns the
com.codename1.ui.plaf.Styleused to paint the slider when its full and selectedReturns
the Style object that shows a completely full style.
-
getSliderEmptyUnselectedStyle
Returns the
com.codename1.ui.plaf.Styleused to paint the slider when its fullReturns
the Style object that shows a completely full style.
-
getSliderEmptySelectedStyle
Returns the
com.codename1.ui.plaf.Styleused to paint the slider when its full and selectedReturns
the Style object that shows a completely full style.
-
getStyle
Returns the current Component Style allowing code to draw the current component, you should normally use getUnselected/Pressed/DisabledStyle() and not this method since it will return different values based on component state.
Returns
the component Style object
-
calcPreferredSize
Return the size we would generally like for the component- Overrides:
calcPreferredSizein classLabel
-
paintComponentBackground
Paint the progress indicator -
isVertical
public boolean isVertical()Indicates the slider is vertical
Returns
true if the slider is vertical
-
setVertical
public void setVertical(boolean vertical) Indicates the slider is vertical
Parameters
vertical: true if the slider is vertical
-
isEditable
public boolean isEditable()Indicates the slider is modifyable
Returns
true if the slider is editable
- Specified by:
isEditablein interfaceEditable- Overrides:
isEditablein classComponent
-
setEditable
public void setEditable(boolean editable) Indicates the slider is modifyable
Parameters
editable: true if the slider is editable
-
pointerPressed
public void pointerPressed(int x, int y) Description copied from class:ComponentIf this Component is focused, the pointer pressed event will call this method
Parameters
-
x: the pointer x coordinate -
y: the pointer y coordinate
- Overrides:
pointerPressedin classComponent
-
-
pointerDragged
public void pointerDragged(int x, int y) If this Component is focused, the pointer dragged event will call this method
Parameters
-
x: the pointer x coordinate -
y: the pointer y coordinate
- Overrides:
pointerDraggedin classComponent
-
-
fireClicked
protected void fireClicked()When working in 3 softbutton mode "fire" key (center softbutton) is sent to this method in order to allow 3 button devices to work properly. When overriding this method you should also override isSelectableInteraction to indicate that a command is placed appropriately on top of the fire key for 3 soft button phones.- Overrides:
fireClickedin classComponent
-
isSelectableInteraction
protected boolean isSelectableInteraction()This method allows a component to indicate that it is interested in an "implicit" select command to appear in the "fire" button when 3 softbuttons are defined in a device.
Returns
true if this is a selectable interaction
- Overrides:
isSelectableInteractionin classComponent
-
pointerReleased
public void pointerReleased(int x, int y) If this Component is focused, the pointer released event will call this method
Parameters
-
x: the pointer x coordinate -
y: the pointer y coordinate
- Overrides:
pointerReleasedin classComponent
-
-
keyReleased
public void keyReleased(int code) If this Component is focused, the key released event will call this method
Parameters
keyCode: the key code value to indicate a physical key.
- Overrides:
keyReleasedin classComponent
-
keyPressed
public void keyPressed(int code) If this Component is focused, the key pressed event will call this method
Parameters
keyCode: the key code value to indicate a physical key.
- Overrides:
keyPressedin classComponent
-
getIncrements
public int getIncrements()The increments when the user presses a key to the left/right/up/down etc.
Returns
increment value
-
setIncrements
public void setIncrements(int increments) The increments when the user presses a key to the left/right/up/down etc.
Parameters
increments: increment value
-
addDataChangedListener
Adds a listener to data changed events, notice that the status argument to the data change listener shouldn't be relied upon.
Parameters
l: new listener
-
removeDataChangedListener
Removes a listener from data changed events, notice that the status argument to the data change listener shouldn't be relied upon.
Parameters
l: listener to remove
-
addActionListener
Action listeners give a more coarse event only when the user lifts the finger from the slider
Parameters
l: the listener
- Specified by:
addActionListenerin interfaceActionSource
-
removeActionListener
Action listeners give a more coarse event only when the user lifts the finger from the slider
Parameters
l: the listener
- Specified by:
removeActionListenerin interfaceActionSource
-
isRenderPercentageOnTop
public boolean isRenderPercentageOnTop()Indicates that the value of the slider should be rendered with a percentage sign on top of the slider.
Returns
true if so
-
setRenderPercentageOnTop
public void setRenderPercentageOnTop(boolean renderPercentageOnTop) Indicates that the value of the slider should be rendered with a percentage sign on top of the slider.
Parameters
renderPercentageOnTop: true to render percentages
-
isRenderValueOnTop
public boolean isRenderValueOnTop()Returns
the renderValueOnTop
-
setRenderValueOnTop
public void setRenderValueOnTop(boolean renderValueOnTop) Parameters
renderValueOnTop: the renderValueOnTop to set
-
getMaxValue
public int getMaxValue()Returns
the maxValue
-
setMaxValue
public void setMaxValue(int maxValue) Parameters
maxValue: the maxValue to set
-
getMinValue
public int getMinValue()Returns
the minValue
-
setMinValue
public void setMinValue(int minValue) Parameters
minValue: the minValue to set
-
getThumbImage
The thumb image is drawn on top of the current progress
Returns
the thumbImage
-
setThumbImage
The thumb image is drawn on top of the current progress
Parameters
thumbImage: the thumbImage to set
-
shouldBlockSideSwipe
protected boolean shouldBlockSideSwipe()A component that might need side swipe such as the slider could block it from being used for some other purpose when on top of said component.- Overrides:
shouldBlockSideSwipein classComponent
-