# Class ChartComponent

java.lang.Object
com.codename1.ui.Component
com.codename1.charts.ChartComponent

All Implemented Interfaces:
  `Animation, Editable, StyleListener`

public class ChartComponent extends Component

The top level component for displaying charts

The `charts` package enables Codename One developers to add charts and visualizations to their apps without having to include external libraries or embedding web views. We also wanted to harness the new features in the graphics pipeline to maximize performance.

Features

- Built-in support for many common types of charts including bar charts, line charts, stacked charts, scatter charts, pie charts and more.

- Pinch Zoom - The `com.codename1.charts,ChartComponent` class includes optional pinch zoom support.

- Panning Support - The `com.codename1.charts,ChartComponent` class includes optional support for panning.

Chart Types

The `com.codename1.charts` package includes models and renderers for many different types of charts. It is also extensible so that you can add your own chart types if required. The following screen shots demonstrate a small sampling of the types of charts that can be created.

**

The above screenshots were taken from the ChartsDemo app. Y ou can start playing with this app by checking it out from our git repository.

How to Create A Chart

Adding a chart to your app involves four steps:

- Build the model. You can construct a model (aka data set) for the chart using one of the existing model classes in the `com.codename1.charts.models` package. Essentially, this is just where you add the data that you want to display.

- Set up a renderer. You can create a renderer for your chart using one of the existing renderer classes in the `com.codename1.charts.renderers` package. The renderer allows you to specify how the chart should look. E.g. the colors, fonts, styles, to use.

- Create the Chart View. Use one of the existing view classes in the `com.codename1.charts.views` package.

- **Create a `com.codename1.charts,ChartComponent` **. In order to add your chart to the UI, you need to wrap it in a `com.codename1.charts,ChartComponent` object.

You can check out the ChartsDemo app for specific examples, but here is a high level view of some code that creates a Pie Chart.

    /**
     * Creates a renderer for the specified colors.
     */
    private DefaultRenderer buildCategoryRenderer(int[] colors) {
        DefaultRenderer renderer = new DefaultRenderer();
        renderer.setLabelsTextSize(15);
        renderer.setLegendTextSize(15);
        renderer.setMargins(new int[]{20, 30, 15, 0});
        for (int color : colors) {
            SimpleSeriesRenderer r = new SimpleSeriesRenderer();
            r.setColor(color);
            renderer.addSeriesRenderer(r);
        }
        return renderer;
    }

    /**
     * Builds a category series using the provided values.
     *
     * @param titles the series titles
     * @param values the values
     * @return the category series
     */
    protected CategorySeries buildCategoryDataset(String title, double[] values) {
        CategorySeries series = new CategorySeries(title);
        int k = 0;
        for (double value : values) {
            series.add("Project " + ++k, value);
        }

        return series;
    }

    public Form createPieChartForm() {
        // Generate the values
        double[] values = new double[]{12, 14, 11, 10, 19};

        // Set up the renderer
        int[] colors = new int[]{ColorUtil.BLUE, ColorUtil.GREEN, ColorUtil.MAGENTA, ColorUtil.YELLOW, ColorUtil.CYAN};
        DefaultRenderer renderer = buildCategoryRenderer(colors);
        renderer.setZoomButtonsVisible(true);
        renderer.setZoomEnabled(true);
        renderer.setChartTitleTextSize(20);
        renderer.setDisplayValues(true);
        renderer.setShowLabels(true);
        SimpleSeriesRenderer r = renderer.getSeriesRendererAt(0);
        r.setGradientEnabled(true);
        r.setGradientStart(0, ColorUtil.BLUE);
        r.setGradientStop(0, ColorUtil.GREEN);
        r.setHighlighted(true);

        // Create the chart ... pass the values and renderer to the chart object.
        PieChart chart = new PieChart(buildCategoryDataset("Project budget", values), renderer);

        // Wrap the chart in a Component so we can add it to a form
        ChartComponent c = new ChartComponent(chart);

        // Create a form and show it.
        Form f = new Form("Budget", new BorderLayout());
        f.add(BorderLayout.CENTER, c);
        return f;

    }

The charts package is derived work from the excellent open source aChartEngine API.

- ## 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
  `ChartComponent(AbstractChart chart)`
  Creates a new chart component to display the provided chart.

- ## Method Summary

  Modifier and Type
  Method
  Description
  `protected Dimension`
  `calcPreferredSize()`
  Calculates the preferred size based on component content.
  `protected void`
  `chartBoundsChanged()`
  Subclasses can override this method to be informed when the chart bounds change due to panning or zooming.
  `Point`
  `chartToScreenCoord(int x, int y)`
  Returns the screen position from a chart coordinate
  `Shape`
  `chartToScreenShape(Shape s)`
  Converts a screen coordinate spaced shape to the same shape in the chart coordinate space
  `void`
  `clearPanLimits()`
  Removes the pan limits which may have been previously set with `double, double, double)`
  `AbstractChart`
  `getChart()`
  Gets the chart that is being displayed in this component.
  `Transform`
  `getTransform()`
  Gets the transform for the chart.
  `boolean`
  `isPanEnabled()`
  Checks if panning is enabled.
  `boolean`
  `isPanXEnabled()`
  Checks whether panning is enabled along the X-axis.
  `boolean`
  `isPanYEnabled()`
  Checks whether panning is enabled along the Y-axis.
  `boolean`
  `isZoomEnabled()`
  Checks whether zoom is enabled.
  `boolean`
  `isZoomXEnabled()`
  Checks whether zoom is enabled on the X-axis.
  `boolean`
  `isZoomYEnabled()`
  Checks whether zoom is enabled on the Y-axis.
  `void`
  `paint(Graphics g)`
  Paints the chart.
  `void`
  `pointerDragged(int[] x, int[] y)`
  If this Component is focused, the pointer dragged event will call this method
  `void`
  `pointerPressed(int x, int y)`
  If this Component is focused, the pointer pressed event will call this method
  `void`
  `pointerReleased(int x, int y)`
  If this Component is focused, the pointer released event will call this method
  `Point`
  `screenToChartCoord(int x, int y)`
  Converts screen coordinates to chart coordinates.
  `Shape`
  `screenToChartShape(Shape s)`
  Converts a chart coordinate spaced shape to the same shape in the screen coordinate space
  `protected void`
  `seriesPressed(SeriesSelection sel)`
  Called when a pointer is pressed on a series in the chart.
  `protected void`
  `seriesReleased(SeriesSelection sel)`
  Called when a pointer is released from a series in the chart.
  `void`
  `setChart(AbstractChart chart)`
  Sets the chart to be displayed in this component.
  `void`
  `setPanEnabled(boolean panEnabled)`

  ###### Parameters

  `void`
  `setPanEnabled(boolean panXEnabled, boolean panYEnabled)`
  Enables or disables pan on x and y axes separately.
  `void`
  `setPanLimits(double minX, double maxX, double minY, double maxY)`
  Sets the pan limits if panning is enabled.
  `void`
  `setTransform(Transform transform)`
  Sets the transform for the chart.
  `void`
  `setZoomEnabled(boolean zoomEnabled)`
  Enables or disables zoom on both x and y axes.
  `void`
  `setZoomEnabled(boolean zoomX, boolean zoomY)`
  Enables or disables zoom on x and y axes separately.
  `void`
  `setZoomLimits(double minRangeX, double maxRangeX, double minRangeY, double maxRangeY)`
  Sets the zoom limits.
  `void`
  `zoomTo(double minX, double maxX, double minY, double maxY, int duration)`
  Zooms the chart in an animated fashion to the specified axis ranges.
  `void`
  `zoomToShapeInChartCoords(Shape s)`
  Zooms the view port to show a specified shape.
  `void`
  `zoomToShapeInChartCoords(Shape s, int duration)`
  Zooms the view port to show a specified shape.

  ### 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, deinitialize, 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, 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, getPropertyNames, getPropertyTypeNames, getPropertyTypes, getPropertyValue, 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, initComponent, 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, isStickyDrag, 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, pointerHover, pointerHoverPressed, pointerHoverReleased, pointerPressed, pointerReleased, putClientProperty, refreshTheme, refreshTheme, refreshTheme, remove, removeDragFinishedListener, removeDragOverListener, removeDropListener, removeFocusListener, removeLongPressListener, removePointerDraggedListener, removePointerPressedListener, removePointerReleasedListener, removeScrollListener, removeStateChangeListener, repaint, repaint, requestFocus, resetFocusable, respondsToPointerEvents, scrollRectToVisible, scrollRectToVisible, setAccessibilityText, setAlwaysTensile, setBlockLead, setBoundPropertyValue, setCellRenderer, setCloudBoundProperty, setCloudDestinationProperty, setComponentState, 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, setPropertyValue, 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, styleChanged, toImage, toString, unbindProperty, updateNativeOverlay, visibleBoundsContains`

  ### Methods inherited from class Object

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

- ## Constructor Details

  - ### ChartComponent

    public ChartComponent(AbstractChart chart)

    Creates a new chart component to display the provided chart.

    ###### Parameters

    - `chart`: The chart to be displayed in this component.

- ## Method Details

  - ### getChart

    public AbstractChart getChart()
    Gets the chart that is being displayed in this component.

  - ### setChart

    public void setChart(AbstractChart chart)

    Sets the chart to be displayed in this component.

    ###### Parameters

    - `chart`

  - ### calcPreferredSize

    protected Dimension calcPreferredSize()
    Description copied from class: `Component`

    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`

  - ### paint

    public void paint(Graphics g)

    Paints the chart.

    ###### Parameters

    - `g`
    Specified by:
      `paint` in interface `Animation`
    Overrides:
      `paint` in class `Component`

  - ### screenToChartCoord

    public Point screenToChartCoord(int x, int y)

    Converts screen coordinates to chart coordinates.

    ###### Parameters

    - `x`: screen x position

    - `y`: screen y position

    ###### Returns

    The chart coordinate corresponding to the given screen coordinate.

  - ### chartToScreenCoord

    public Point chartToScreenCoord(int x, int y)

    Returns the screen position from a chart coordinate

    ###### Parameters

    - `x`: the x position within the chart

    - `y`: the y position within the chart

    ###### Returns

    a position within the screen

  - ### screenToChartShape

    public Shape screenToChartShape(Shape s)

    Converts a chart coordinate spaced shape to the same shape in the screen coordinate space

    ###### Parameters

    - `s`: shape in screen coordinates

    ###### Returns

    same shape using chart space coordinates

  - ### chartToScreenShape

    public Shape chartToScreenShape(Shape s)

    Converts a screen coordinate spaced shape to the same shape in the chart coordinate space

    ###### Parameters

    - `s`: shape in chart coordinates

    ###### Returns

    same shape using screen coordinate space

  - ### zoomToShapeInChartCoords

    public void zoomToShapeInChartCoords(Shape s)

    Zooms the view port to show a specified shape. The shape should be expressed in chart coordinates (not screen coordinates).

    ###### Parameters

    - `s`: The shape that should be shown.

  - ### zoomToShapeInChartCoords

    public void zoomToShapeInChartCoords(Shape s, int duration)

    Zooms the view port to show a specified shape. The shape should be expressed in chart coordinates (not screen coordinates).

    ###### Parameters

    - `s`: The shape that should be shown.

    - `duration`: The duration of the transition.

    ###### See also

    - #zoomTo(double, double, double, double, int)

  - ### zoomTo

    public void zoomTo(double minX, double maxX, double minY, double maxY, int duration)

    Zooms the chart in an animated fashion to the specified axis ranges. This is effectively the same as using `int)` except it allows you to specify coordinates as doubles.

    ###### Parameters

    - `minX`: The lower bound of the X-axis after zoom.

    - `maxX`: The upper bound of the X-axis after zoom.

    - `minY`: The lower bound of the Y-axis after zoom.

    - `maxY`: THe upper bound of the Y-axis after zoom.

    - `duration`: Transition time (ms).

  - ### pointerPressed

    public void pointerPressed(int x, int y)
    Description copied from class: `Component`

    If this Component is focused, the pointer pressed event will call this method

    ###### Parameters

    - `x`: the pointer x coordinate

    - `y`: the pointer y coordinate

    Overrides:
      `pointerPressed` in class `Component`

  - ### seriesPressed

    protected void seriesPressed(SeriesSelection sel)

    Called when a pointer is pressed on a series in the chart. This can be overridden by subclasses to respond to this event.

    ###### Parameters

    - `sel`

  - ### pointerReleased

    public void pointerReleased(int x, int y)
    Description copied from class: `Component`

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

  - ### seriesReleased

    protected void seriesReleased(SeriesSelection sel)

    Called when a pointer is released from a series in the chart. This can be overridden in subclasses to handle these events.

    ###### Parameters

    - `sel`

  - ### getTransform

    public Transform getTransform()

    Gets the transform for the chart. This can be used to scale, translate, and rotate the chart. This transform assumes its origin at the (absoluteX, absoluteY) of the component at the time it is drawn rather than the screen's origin as is normally the case with transforms. This allows the transform to be applied consistently with respect to the chart's coordinates even when the component is moved around the screen.

    ###### Returns

    The transform for the chart in component coordinates.

  - ### setTransform

    public void setTransform(Transform transform)

    Sets the transform for the chart. Transforms origin assumed to be at (getAbsoluteX, getAbsoluteY).

    ###### Parameters

    - `transform`: the transform to set

  - ### pointerDragged

    public void pointerDragged(int[] x, int[] y)
    Description copied from class: `Component`

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

  - ### isPanEnabled

    public boolean isPanEnabled()

    Checks if panning is enabled.

    ###### Returns

    the panEnabled

  - ### setPanEnabled

    public void setPanEnabled(boolean panEnabled)

    ###### Parameters

    - `panEnabled`: the panEnabled to set

  - ### setPanEnabled

    public void setPanEnabled(boolean panXEnabled, boolean panYEnabled)

    Enables or disables pan on x and y axes separately. Pass a different value for each axis to lock panning to a single direction; for example `setPanEnabled(true, false)` lets the user pan left/right but pins the Y axis (a useful pattern for time-series charts).

    ###### Parameters

    - `panXEnabled`: True to enable panning along the x-axis.

    - `panYEnabled`: True to enable panning along the y-axis.

  - ### isPanXEnabled

    public boolean isPanXEnabled()
    Checks whether panning is enabled along the X-axis.

  - ### isPanYEnabled

    public boolean isPanYEnabled()
    Checks whether panning is enabled along the Y-axis.

  - ### setPanLimits

    public void setPanLimits(double minX, double maxX, double minY, double maxY)

    Sets the pan limits if panning is enabled.

    ###### Parameters

    - `minX`: The minimum X-axis value for panning.

    - `maxX`: The maximum X-axis value for panning.

    - `minY`: The minimum Y-axis value for panning.

    - `maxY`: The maximum Y-axis value for panning.

  - ### clearPanLimits

    public void clearPanLimits()
    Removes the pan limits which may have been previously set with `double, double, double)`

  - ### isZoomEnabled

    public boolean isZoomEnabled()

    Checks whether zoom is enabled.

    ###### Returns

    the zoomEnabled

  - ### setZoomEnabled

    public void setZoomEnabled(boolean zoomEnabled)

    Enables or disables zoom on both x and y axes.

    ###### Parameters

    - `zoomEnabled`: the zoomEnabled to set

  - ### isZoomXEnabled

    public boolean isZoomXEnabled()
    Checks whether zoom is enabled on the X-axis.

  - ### isZoomYEnabled

    public boolean isZoomYEnabled()
    Checks whether zoom is enabled on the Y-axis.

  - ### setZoomLimits

    public void setZoomLimits(double minRangeX, double maxRangeX, double minRangeY, double maxRangeY)

    Sets the zoom limits.

    NOTE: This method is only applicable when showing an `XYChart` It will throw a RuntimeException if called while a different kind of chart is being shown.

    ###### Parameters

    - `minRangeX`: @param minRangeX The minimum distance from `XYMultipleSeriesRenderer#getXAxisMin()` to `XYMultipleSeriesRenderer#getXAxisMax()` that can be achieved by zooming in. 0 means no limit.

    - `maxRangeX`: @param maxRangeX The maximum distance from `XYMultipleSeriesRenderer#getXAxisMin()` to `XYMultipleSeriesRenderer#getXAxisMax()` that can be achieved by zooming out. 0 means no limit.

    - `minRangeY`: @param minRangeY The minimum distance from `XYMultipleSeriesRenderer#getYAxisMin()` to `XYMultipleSeriesRenderer#getYAxisMax()` that can be achieved by zooming in. 0 means no limit.

    - `maxRangeY`: @param maxRangeY The maximum distance from `XYMultipleSeriesRenderer#getYAxisMin()` to `XYMultipleSeriesRenderer#getYAxisMax()` that can be achieved by zooming out. 0 means no limit.

  - ### setZoomEnabled

    public void setZoomEnabled(boolean zoomX, boolean zoomY)

    Enables or disables zoom on x and y axes separately.

    ###### Parameters

    - `zoomX`: True to enable zooming x axis.

    - `zoomY`: True to enable zooming y axis.

  - ### chartBoundsChanged

    protected void chartBoundsChanged()
    Subclasses can override this method to be informed when the chart bounds change due to panning or zooming.