public class Switch

  1. Object
  2. Component
  3. Switch

ImplementsActionSource, Animation, Editable, ReleasableComponent, StyleListener

The on/off switch is a checkbox of sort (although it derives container) that represents its state as a switch When using the Android native theme, this implementation follows the Material Design Switch guidelines: https://material.io/guidelines/components/selection-controls.html#selection-controls-radio-button

Customizing Look and Feel

You can customize the look and feel of a switch using styles, either directly in the theme.res file or in CSS. This component consists of two elements: the “thumb” the “track”. The “thumb” is the circular handle that can be toggled/dragged between an on and off position. The “track” is the background track along which the “thumb” appears to slide when it is dragged/toggled.

The thumb will be rendered using Switch’s Style#getFgColor(). It will use the selected style, when in the “on” position, the unselected style when in the “off” position, and the disabled style, when #isEnabled() is false.

The track will be rendered using the Switch’s Style#getBgColor(). It will use the selected style, when in the “on” position, and the unselected style when in the “off” position.

You can also adjust the thumb and track sizes using the following theme constants:

switchThumbScaleYA floating point value used to scale the thumb’s diameter, relative to the font size. In the android native theme, this value is set to 1.5. On iOS, it is set to 1.4. switchTrackScaleYA floating point value used to scale the track’s height, relative the the font size. In the android native theme, this value is set to 0.9. On iOS, it is set to 1.5 switchTrackScaleXA floating point value used to scale the track’s width relative to the font size. In the Android native theme, this value is set to 3.0. On iOS it is 2.5 switchTrackOffOutlineWidthMMA floating point value used to set the stroke/outline thickness of the track when the switch is in the “off” position. In the Android native theme, this is set to 0. On iOS it is 0.25 switchTrackOnOutlineWidthMMA floating point value used to set the stroke/outline thickness of the track when the switch is in the “on” position. In both the Android native theme and the iOS native theme, this is set to 0. switchTrackOffOutlineColorThe color used to stroke the outline for the track when the switch is in the “off” position, expressed as a base-16 int. In the iOS native theme, this is set to “cccccc”. switchTrackOnOutlineColorThe color used to stroke the outline for the track when the switch is in the “on” position, expressed as a base-16 int. This is currently not used in either Android or iOS. switchThumbInsetMMAn inset to use when rendering the thumb that will cause it to be inset from the edge of the track. In the iOS native theme, this is 0.25

IMPORTANT: when changing the UIID of the switch the constants above implicitly change to match the new UIID with the same convetion. So if your UIID is MySwitch then a theme constant will become: myswitchTrackScaleY. Notice that the whole UIID is lower cased…

CSS used in the Android native theme:

`#Constants {
...
switchThumbPaddingInt: 2;
switchThumbScaleY: "1.5";
switchTrackScaleY: "0.9";
switchTrackScaleX: "3";
switchTrackOffOutlineWidthMM: "0";
switchTrackOnOutlineWidthMM: "0";
switchTrackOffOutlineColor: "cccccc";
switchThumbInsetMM: "0";`
Switch {
color: rgb(237, 237, 237);
background-color: rgb(159, 158, 158);

}
Switch.selected {
color: rgb(34,44,50);
background-color: rgb(117, 126, 132);
}
}

CSS used in the iOS native theme:

`#Constants {
...
switchThumbPaddingInt: 2;
switchThumbScaleY: "1.4";
switchTrackScaleY: "1.5";
switchTrackScaleX: "2.5";
switchTrackOffOutlineWidthMM: "0.25";
switchTrackOnOutlineWidthMM: "0";
switchTrackOffOutlineColor: "cccccc";
switchThumbInsetMM: "0.25";`
Switch {
color: white;
background-color: white;

}
Switch.selected {
color: white;
background-color: rgb(61, 216, 76);

}
}

Using Custom Thumb and Track Images

You can optionally provide custom images for use as the track or thumb via the following theme constants

  • switchThumbOnImage

  • switchThumbOffImage

  • switchThumbDisabledImage

  • switchOnTrackImage

  • switchOffTrackImage

  • switchDisabledTrackImage

Constructors

public Switch()Default constructor
public Switch(String uiid)This constructor should be used when customizing theme constants for a different UIID

Methods

protected int getDragRegionStatus(int x, int y)Indicates if the section within the X/Y area is a “drag region” where we expect people to drag or press in which case we can instantly start dragging making perceived performance faster.
public void styleChanged(String propertyName, Style source)Invoked to indicate a change in a propertyName of a Style
protected Dimension calcPreferredSize()Calculates the preferred size based on component content.
protected void resetFocusable()Restores the state of the focusable flag to its default state
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!
protected boolean isStickyDrag()Returns true if the component is interested in receiving drag/pointer release events even after the gesture exceeded its boundaries.
public void addActionListener(ActionListener l)Adds a listener to the switch which will cause an event to dispatch on click
public void removeActionListener(ActionListener l)Removes the given action listener from the switch
public void addChangeListener(ActionListener l)Adds a listener to the switch which will cause an event on change
public void removeChangeListener(ActionListener l)Removes the given change listener from the switch
public Collection getListeners()Deprecated Returns a collection containing the action listeners for this button
public void setMorphTestProgress(float progress)TEST-ONLY hook: render the thumb slide frozen at a fixed progress (0 = resting OFF .. 1 = the ON end) instead of the live drag state, so a fidelity probe can capture exact deterministic frames of the liquid-glass droplet animation without racing the real-time motion.
public void paint(Graphics g)This method paints the Component on the screen, it should be overriden by subclasses to perform custom drawing or invoke the UI API’s to let the PLAF perform the rendering.
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 boolean isValue()The value of the switch
public void setValue(boolean value)The value of the switch
public boolean isOn()Checks if switch is in the “on” position.
public void setOn()Sets the switch to the “on” position.
public boolean isOff()Checks if the switch is in the “off” position.
public void setOff()Switches the switch to the “off” position.
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 Object getComponentState()Some components may optionally generate a state which can then be restored using setCompnentState().
public void setComponentState(Object state)If getComponentState returned a value the setter can update the value and restore the prior state.
public Class[] getPropertyTypes()Matches the property names method (see that method for further details).
public Object getPropertyValue(String name)Returns the current value of the property name, this method is used by the GUI builder
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 isAutoRelease()Returns true if this is an auto-released Component.
public void setAutoRelease(boolean arg0)Sets the auto released mode of the Component
public int getReleaseRadius()Indicates a radius in which a pointer release will still have effect.
public void setReleaseRadius(int arg0)Indicates a radius in which a pointer release will still have effect.
public void setReleased()Function that would be called by the parent Form to put the Component in its released state

Inherited fields

Inherited methods

From Component

setSameSize, isSetCursorSupported, parsePreferredSize, getDefaultDragTransparency, setDefaultDragTransparency, getEditingDelegate, setEditingDelegate, getCursor, setCursor, showNativeOverlay, hideNativeOverlay, updateNativeOverlay, getNativeOverlay, getAllStyles, getSameWidth, setSameWidth, getSameHeight, setSameHeight, initLaf, getUIManager, getX, setX, getOuterX, getInnerX, getY, setY, getOuterY, getInnerY, isVisible, setVisible, getClientProperty, stripMarginAndPadding, clearClientProperties, putClientProperty, getDirtyRegion, setDirtyRegion, isOpaque, setOpaque, getWidth, setWidth, getOuterWidth, getInnerWidth, getHeight, setHeight, getOuterHeight, getInnerHeight, isDragRegion, getBaseline, getBaselineResizeBehavior, getPreferredSizeStr, setPreferredSizeStr, getPreferredSize, setPreferredSize, getScrollDimension, calcScrollSize, 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, fireClicked, isSelectableInteraction, getSelectCommandText, setSelectCommandText, getLabelForComponent, setLabelForComponent, focusGained, focusLost, paintBackgrounds, paintShadows, getAbsoluteX, getAbsoluteY, isInClippingRegion, paintIntersectingComponentsAbove, paintScrollbars, paintScrollbarX, getScrollOpacity, getSelectedRect, paintScrollbarY, paintComponent, paintComponent, getBorder, getScrollable, paintBackground, isScrollable, isScrollableX, isScrollableY, getScrollX, setScrollX, getScrollY, setScrollY, onScrollX, onScrollY, getDraggedx, getDraggedy, getBottomGap, getSideGap, contains, visibleBoundsContains, hasFixedPreferredSize, getBounds, getBounds, getVisibleBounds, getVisibleBounds, isFocusable, setFocusable, onSetFocusable, getTabIndex, setTabIndex, getPreferredTabIndex, setPreferredTabIndex, isTraversable, setTraversable, setShouldCalcPreferredSize, handlesInput, setHandlesInput, consumesRawTextInput, hasFocus, setFocus, getComponentForm, getTopLevelContainer, repaint, repaint, longKeyPress, keyPressed, keyReleased, keyRepeated, registerForAnimation, deregisterFromAnimation, getAnimationManager, getScrollAnimationSpeed, setScrollAnimationSpeed, isBlockLead, setBlockLead, isIgnorePointerEvents, setIgnorePointerEvents, isRippleEffect, setRippleEffect, getInlineStylesTheme, setInlineStylesTheme, shouldRenderComponentSelection, isHideInLandscape, setHideInLandscape, createStyleAnimation, isSmoothScrolling, setSmoothScrolling, pointerHover, stopScrollMomentum, pointerHoverReleased, pointerHoverPressed, pinch, pinchReleased, pinch, rotation, isPinchBlocksDragAndDrop, setPinchBlocksDragAndDrop, pointerDragged, getDragImage, getDragTransparency, setDragTransparency, toImage, dragInitiated, drawDraggedImage, draggingOver, dragEnter, dragExit, drop, addPullToRefresh, setPullToRefresh, respondsToPointerEvents, pointerDragged, pointerPressed, isDragAndDropOperation, pointerPressed, pointerReleased, longPointerPress, pointerReleased, setVerticalScrollBounds, setHorizontalScrollBounds, isVScrollThumbGrabbed, isHScrollThumbGrabbed, isVScrollThumbHover, isHScrollThumbHover, isTensileDragEnabled, setTensileDragEnabled, getTextSelectionSupport, 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, getStyle, getPressedStyle, setPressedStyle, initUnselectedStyle, initPressedStyle, initDisabledStyle, initSelectedStyle, getUnselectedStyle, setUnselectedStyle, getSelectedStyle, setSelectedStyle, getDisabledStyle, setDisabledStyle, installDefaultPainter, requestFocus, toString, paramString, refreshTheme, refreshTheme, isDragActivated, getGridPosY, getGridPosX, animate, scrollRectToVisible, scrollRectToVisible, paintBorder, paintBorderBackground, isCellRenderer, setCellRenderer, isScrollVisible, setScrollVisible, setIsScrollVisible, startEditingAsync, stopEditing, isEditing, isEditable, laidOut, isInitialized, setInitialized, getNextFocusDown, setNextFocusDown, getNextFocusUp, setNextFocusUp, getNextFocusLeft, setNextFocusLeft, getNextFocusRight, setNextFocusRight, isEnabled, setEnabled, getName, setName, initCustomStyle, deinitializeCustomStyle, isRTL, setRTL, isTactileTouch, isTactileTouch, setTactileTouch, getPropertyTypeNames, 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, getBindablePropertyNames, getBindablePropertyTypes, bindProperty, unbindProperty, getBoundPropertyValue, setBoundPropertyValue, getCloudBoundProperty, setCloudBoundProperty, getCloudDestinationProperty, setCloudDestinationProperty, setHidden, isHidden, setHidden, isHidden, announceForAccessibility, getAccessibilityText, setAccessibilityText, getSemantics, getAccessibilityNode, accessibilityChanged, accessibilityChanged, getTooltip, setTooltip

Constructor details

Switch

public Switch()
Default constructor

Switch

public Switch(String uiid)
This constructor should be used when customizing theme constants for a different UIID

Parameters

uiid String
accepts an alternate UIID for switch which might be necessary for theme constants

Method details

getDragRegionStatus

protected int getDragRegionStatus(int x, int y)
Indicates if the section within the X/Y area is a “drag region” where we expect people to drag or press in which case we can instantly start dragging making perceived performance faster. This is invoked by the implementation code to optimize drag start behavior

Parameters

x int
x location for the touch
y int
y location for the touch

Returns

one of the DRAG_REGION_* values

styleChanged

public void styleChanged(String propertyName, Style source)

Invoked to indicate a change in a propertyName of a Style

NOTE By default this will trigger a call to Container#revalidate() on the parent container, which is expensive. You can disable this behavior by calling CN.setProperty("Component.revalidateOnStyleChange", "false"). The intention is to change this behavior so that the default is to “not” revalidate on style change, so we encourage you to set this to “false” to ensure for future compatibility.

Parameters

propertyName String
the property name that was changed
source Style
The changed Style object

calcPreferredSize

protected Dimension calcPreferredSize()
Calculates the preferred size based on component content. This method is invoked lazily by getPreferred size.

Returns

the calculated preferred size based on component content

resetFocusable

protected void resetFocusable()
Restores the state of the focusable flag to its default state

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 boolean
indicates if the current styles should be merged with the new styles

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

addActionListener

public void addActionListener(ActionListener l)
Adds a listener to the switch which will cause an event to dispatch on click

Parameters

l ActionListener
implementation of the action listener interface

removeActionListener

public void removeActionListener(ActionListener l)
Removes the given action listener from the switch

Parameters

l ActionListener
implementation of the action listener interface

addChangeListener

public void addChangeListener(ActionListener l)
Adds a listener to the switch which will cause an event on change

Parameters

l ActionListener
implementation of the action listener interface

removeChangeListener

public void removeChangeListener(ActionListener l)
Removes the given change listener from the switch

Parameters

l ActionListener
implementation of the action listener interface

getListeners

public Collection getListeners()
Deprecated. This will be removed in a future version.
Returns a collection containing the action listeners for this button

Returns

the action listeners

setMorphTestProgress

public void setMorphTestProgress(float progress)
TEST-ONLY hook: render the thumb slide frozen at a fixed progress (0 = resting OFF .. 1 = the ON end) instead of the live drag state, so a fidelity probe can capture exact deterministic frames of the liquid-glass droplet animation without racing the real-time motion. Assumes the switch is in the OFF state (the frame travels OFF -> ON). Pass a negative value to clear and resume normal behaviour.

paint

public void paint(Graphics g)
This method paints the Component on the screen, it should be overriden by subclasses to perform custom drawing or invoke the UI API’s to let the PLAF perform the rendering.

Parameters

g Graphics
the component graphics

initComponent

protected void initComponent()
Allows subclasses to bind functionality that relies on fully initialized and “ready for action” component state

deinitialize

protected 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.

isValue

public boolean isValue()
The value of the switch

Returns

the value

setValue

public void setValue(boolean value)
The value of the switch

Parameters

value boolean
the value to set

isOn

public boolean isOn()
Checks if switch is in the “on” position.

Returns

True if switch is on.

setOn

public void setOn()
Sets the switch to the “on” position.

isOff

public boolean isOff()
Checks if the switch is in the “off” position.

Returns

True of switch is currently off.

setOff

public void setOff()
Switches the switch to the “off” position.

getPropertyNames

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

Returns

the property names allowing mutation

getComponentState

public Object getComponentState()
Some components may optionally generate a state which can then be restored using setCompnentState(). This method is used by the UIBuilder.

Returns

the component state or null for undefined state.

setComponentState

public void setComponentState(Object state)
If getComponentState returned a value the setter can update the value and restore the prior state.

Parameters

state Object
the non-null state

getPropertyTypes

public Class[] getPropertyTypes()
Matches the property names method (see that method for further details).

Returns

the types of the properties

getPropertyValue

public Object getPropertyValue(String name)
Returns the current value of the property name, this method is used by the GUI builder

Parameters

name String
the name of the property

Returns

the value of said property

setPropertyValue

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. Notice that some builtin properties such as “$designMode” might be sent to components to indicate application state.

Parameters

name String
the name of the property
value Object
new value for the property

Returns

error message or null

isAutoRelease

public boolean isAutoRelease()
Returns true if this is an auto-released Component. An Auto-released Component will be disarmed when a drag is happening within it

setAutoRelease

public void setAutoRelease(boolean arg0)
Sets the auto released mode of the Component

getReleaseRadius

public int getReleaseRadius()
Indicates a radius in which a pointer release will still have effect. Notice that this only applies to pointer release events and not to pointer press events

Returns

the releaseRadius

setReleaseRadius

public void setReleaseRadius(int arg0)
Indicates a radius in which a pointer release will still have effect. Notice that this only applies to pointer release events and not to pointer press events

Parameters

arg0 int
the releaseRadius to set

setReleased

public void setReleased()
Function that would be called by the parent Form to put the Component in its released state