# Class Switch

java.lang.Object
com.codename1.ui.Component
com.codename1.components.Switch

All Implemented Interfaces:
  `Animation, Editable, ActionSource, StyleListener, ReleasableComponent`

public class Switch extends Component implements ActionSource, ReleasableComponent

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

- ## 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
  `Switch()`
  Default constructor
  `Switch(String uiid)`
  This constructor should be used when customizing theme constants for a different UIID

- ## Method Summary

  Modifier and Type
  Method
  Description
  `void`
  `addActionListener(ActionListener l)`
  Adds a listener to the switch which will cause an event to dispatch on click
  `void`
  `addChangeListener(ActionListener l)`
  Adds a listener to the switch which will cause an event on change
  `protected Dimension`
  `calcPreferredSize()`
  Calculates the preferred size based on component content.
  `protected void`
  `deinitialize()`
  Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy.
  `Object`
  `getComponentState()`
  Some components may optionally generate a state which can then be restored using setCompnentState().
  `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.
  `Collection`
  `getListeners()`
  Returns a collection containing the action listeners for this button
  `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
  `Class[]`
  `getPropertyTypes()`
  Matches the property names method (see that method for further details).
  `Object`
  `getPropertyValue(String name)`
  Returns the current value of the property name, this method is used by the GUI builder
  `int`
  `getReleaseRadius()`
  Indicates a radius in which a pointer release will still have effect.
  `protected void`
  `initComponent()`
  Allows subclasses to bind functionality that relies on fully initialized and "ready for action" component state
  `boolean`
  `isAutoRelease()`
  Returns true if this is an auto-released Component.
  `boolean`
  `isOff()`
  Checks if the switch is in the "off" position.
  `boolean`
  `isOn()`
  Checks if switch is in the "on" position.
  `protected boolean`
  `isStickyDrag()`
  Returns true if the component is interested in receiving drag/pointer release events even after the gesture exceeded its boundaries.
  `boolean`
  `isValue()`
  The value of the switch
  `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.
  `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!
  `void`
  `removeActionListener(ActionListener l)`
  Removes the given action listener from the switch
  `void`
  `removeChangeListener(ActionListener l)`
  Removes the given change listener from the switch
  `protected void`
  `resetFocusable()`
  Restores the state of the focusable flag to its default state
  `void`
  `setAutoRelease(boolean arg0)`
  Sets the auto released mode of the Component
  `void`
  `setComponentState(Object state)`
  If getComponentState returned a value the setter can update the value and restore the prior state.
  `void`
  `setOff()`
  Switches the switch to the "off" position.
  `void`
  `setOn()`
  Sets the switch to the "on" position.
  `String`
  `setPropertyValue(String name, Object value)`
  Sets a new value to the given property, returns an error message if failed and null if successful.
  `void`
  `setReleased()`
  Function that would be called by the parent Form to put the Component in its released state
  `void`
  `setReleaseRadius(int arg0)`
  Indicates a radius in which a pointer release will still have effect.
  `void`
  `setValue(boolean value)`
  The value of the switch
  `void`
  `styleChanged(String propertyName, Style source)`
  Invoked to indicate a change in a propertyName of a Style

  ### Methods inherited from class Component

  `addDragFinishedListener, addDragOverListener, addDropListener, addFocusListener, addLongPressListener, addPointerDraggedListener, addPointerPressedListener, addPointerReleasedListener, addPullToRefresh, addScrollListener, addStateChangeListener, animate, announceForAccessibility, bindProperty, blocksSideSwipe, calcScrollSize, cancelRepaints, clearClientProperties, contains, containsOrOwns, createStyleAnimation, deinitializeCustomStyle, dragEnter, dragExit, dragFinished, draggingOver, dragInitiated, drawDraggedImage, drop, fireClicked, focusGained, focusLost, getAbsoluteX, getAbsoluteY, getAccessibilityText, getAllStyles, getAnimationManager, getBaseline, getBaselineResizeBehavior, getBindablePropertyNames, getBindablePropertyTypes, getBorder, getBottomGap, getBoundPropertyValue, getBounds, getBounds, getClientProperty, getCloudBoundProperty, getCloudDestinationProperty, getComponentForm, getCursor, getDefaultDragTransparency, getDirtyRegion, getDisabledStyle, getDraggedx, getDraggedy, getDragImage, 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, getPropertyTypeNames, getSameHeight, getSameWidth, getScrollable, getScrollAnimationSpeed, getScrollDimension, getScrollOpacity, getScrollOpacityChangeSpeed, getScrollX, getScrollY, getSelectCommandText, getSelectedRect, getSelectedStyle, getSideGap, getStyle, getTabIndex, getTensileLength, getTextSelectionSupport, getTooltip, getUIID, getUIManager, getUnselectedStyle, getVisibleBounds, getVisibleBounds, getWidth, getX, getY, growShrink, handlesInput, hasFixedPreferredSize, hasFocus, hideNativeOverlay, initCustomStyle, initDisabledStyle, initLaf, initPressedStyle, initSelectedStyle, initUnselectedStyle, installDefaultPainter, isAlwaysTensile, isBlockLead, isCellRenderer, isChildOf, isDragActivated, isDragAndDropOperation, isDraggable, isDragRegion, isDropTarget, isEditable, isEditing, isEnabled, isFlatten, isFocusable, isGrabsPointerEvents, isHidden, isHidden, isHideInLandscape, isHideInPortrait, isIgnorePointerEvents, isInClippingRegion, isInitialized, isOpaque, isOwnedBy, isPinchBlocksDragAndDrop, isRippleEffect, isRTL, isScrollable, isScrollableX, isScrollableY, isScrollVisible, isSelectableInteraction, isSetCursorSupported, isSmoothScrolling, isSnapToGrid, isTactileTouch, isTactileTouch, isTensileDragEnabled, isTraversable, isVisible, keyPressed, keyReleased, keyRepeated, laidOut, longKeyPress, longPointerPress, onScrollX, onScrollY, onSetFocusable, paintBackground, paintBackgrounds, paintBorder, paintBorderBackground, paintComponent, paintComponent, paintIntersectingComponentsAbove, paintLock, paintLockRelease, paintRippleOverlay, paintScrollbars, paintScrollbarX, paintScrollbarY, paintShadows, paramString, parsePreferredSize, pinch, pinch, pinchReleased, pointerDragged, pointerDragged, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerPressed, pointerReleased, pointerReleased, putClientProperty, refreshTheme, refreshTheme, remove, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, repaint, repaint, requestFocus, respondsToPointerEvents, scrollRectToVisible, scrollRectToVisible, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCellRenderer, setCloudBoundProperty, setCloudDestinationProperty, setCursor, setDefaultDragTransparency, setDirtyRegion, setDisabledStyle, setDraggable, setDragTransparency, setDropTarget, setEditingDelegate, setEnabled, 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, setPullToRefresh, setRippleEffect, setRTL, setSameHeight, setSameSize, setSameWidth, setScrollAnimationSpeed, setScrollOpacityChangeSpeed, setScrollSize, setScrollVisible, setScrollX, setScrollY, setSelectCommandText, setSelectedStyle, setShouldCalcPreferredSize, 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, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains`

  ### Methods inherited from class Object

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

- ## 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`: @param uiid accepts an alternate UIID for switch which might be necessary for theme constants

- ## Method Details

  - ### getDragRegionStatus

    protected int getDragRegionStatus(int x, int y)
    Description copied from class: `Component`

    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`: x location for the touch

    - `y`: y location for the touch

    ###### Returns

    one of the DRAG_REGION_* values

    Overrides:
      `getDragRegionStatus` in class `Component`

  - ### 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`: the property name that was changed

    - `source`: The changed Style object

    Specified by:
      `styleChanged` in interface `StyleListener`
    Overrides:
      `styleChanged` in class `Component`

  - ### 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

    Overrides:
      `calcPreferredSize` in class `Component`

  - ### resetFocusable

    protected void resetFocusable()
    Restores the state of the focusable flag to its default state
    Overrides:
      `resetFocusable` in class `Component`

  - ### 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:
      `refreshTheme` in class `Component`

  - ### 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:
      `isStickyDrag` in class `Component`

  - ### addActionListener

    public void addActionListener(ActionListener l)

    Adds a listener to the switch which will cause an event to dispatch on click

    ###### Parameters

    - `l`: implementation of the action listener interface
    Specified by:
      `addActionListener` in interface `ActionSource`

  - ### removeActionListener

    public void removeActionListener(ActionListener l)

    Removes the given action listener from the switch

    ###### Parameters

    - `l`: implementation of the action listener interface
    Specified by:
      `removeActionListener` in interface `ActionSource`

  - ### addChangeListener

    public void addChangeListener(ActionListener l)

    Adds a listener to the switch which will cause an event on change

    ###### Parameters

    - `l`: implementation of the action listener interface

  - ### removeChangeListener

    public void removeChangeListener(ActionListener l)

    Removes the given change listener from the switch

    ###### Parameters

    - `l`: implementation of the action listener interface

  - ### getListeners

    public Collection getListeners()

    Returns a collection containing the action listeners for this button

    ###### Returns

    the action listeners

    ###### Deprecated

    This will be removed in a future version.

  - ### 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`: the component graphics
    Specified by:
      `paint` in interface `Animation`
    Overrides:
      `paint` in class `Component`

  - ### initComponent

    protected void initComponent()
    Allows subclasses to bind functionality that relies on fully initialized and "ready for action" component state
    Overrides:
      `initComponent` in class `Component`

  - ### 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.
    Overrides:
      `deinitialize` in class `Component`

  - ### 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`: 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

    Overrides:
      `getPropertyNames` in class `Component`

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

    Overrides:
      `getComponentState` in class `Component`

  - ### setComponentState

    public void setComponentState(Object state)

    If getComponentState returned a value the setter can update the value and restore the prior state.

    ###### Parameters

    - `state`: the non-null state
    Overrides:
      `setComponentState` in class `Component`

  - ### getPropertyTypes

    public Class[] getPropertyTypes()

    Matches the property names method (see that method for further details).

    ###### Returns

    the types of the properties

    Overrides:
      `getPropertyTypes` in class `Component`

  - ### getPropertyValue

    public Object getPropertyValue(String name)

    Returns the current value of the property name, this method is used by the GUI builder

    ###### Parameters

    - `name`: the name of the property

    ###### Returns

    the value of said property

    Overrides:
      `getPropertyValue` in class `Component`

  - ### 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`: the name of the property

    - `value`: new value for the property

    ###### Returns

    error message or null

    Overrides:
      `setPropertyValue` in class `Component`

  - ### 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
    Specified by:
      `isAutoRelease` in interface `ReleasableComponent`

  - ### setAutoRelease

    public void setAutoRelease(boolean arg0)
    Sets the auto released mode of the Component
    Specified by:
      `setAutoRelease` in interface `ReleasableComponent`

  - ### 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

    Specified by:
      `getReleaseRadius` in interface `ReleasableComponent`

  - ### 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

    - `releaseRadius`: the releaseRadius to set
    Specified by:
      `setReleaseRadius` in interface `ReleasableComponent`

  - ### setReleased

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