public class ChartComponent

  1. Object
  2. Component
  3. ChartComponent

ImplementsAnimation, Editable, StyleListener

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.

Constructors

public ChartComponent(AbstractChart chart)Creates a new chart component to display the provided chart.

Methods

public AbstractChart getChart()Gets the chart that is being displayed in this component.
public void setChart(AbstractChart chart)Sets the chart to be displayed in this component.
protected Dimension calcPreferredSize()Calculates the preferred size based on component content.
public void paint(Graphics g)Paints the chart.
public Point screenToChartCoord(int x, int y)Converts screen coordinates to chart coordinates.
public Point chartToScreenCoord(int x, int y)Returns the screen position from a chart coordinate
public Shape screenToChartShape(Shape s)Converts a chart coordinate spaced shape to the same shape in the screen coordinate space
public Shape chartToScreenShape(Shape s)Converts a screen coordinate spaced shape to the same shape in the chart coordinate space
public void zoomToShapeInChartCoords(Shape s)Zooms the view port to show a specified shape.
public void zoomToShapeInChartCoords(Shape s, int duration)Zooms the view port to show a specified shape.
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.
public void pointerPressed(int x, int y)If this Component is focused, the pointer pressed event will call this method
protected void seriesPressed(SeriesSelection sel)Called when a pointer is pressed on a series in the chart.
public void pointerReleased(int x, int y)If this Component is focused, the pointer released event will call this method
protected void seriesReleased(SeriesSelection sel)Called when a pointer is released from a series in the chart.
public Transform getTransform()Gets the transform for the chart.
public void setTransform(Transform transform)Sets the transform for the chart.
public void pointerDragged(int[] x, int[] y)If this Component is focused, the pointer dragged event will call this method
public boolean isPanEnabled()Checks if panning is enabled.
public void setPanEnabled(boolean panEnabled)
public void setPanEnabled(boolean panXEnabled, boolean panYEnabled)Enables or disables pan on x and y axes separately.
public boolean isPanXEnabled()Checks whether panning is enabled along the X-axis.
public boolean isPanYEnabled()Checks whether panning is enabled along the Y-axis.
public void setPanLimits(double minX, double maxX, double minY, double maxY)Sets the pan limits if panning is enabled.
public void clearPanLimits()Removes the pan limits which may have been previously set with double, double, double)
public boolean isZoomEnabled()Checks whether zoom is enabled.
public void setZoomEnabled(boolean zoomEnabled)Enables or disables zoom on both x and y axes.
public boolean isZoomXEnabled()Checks whether zoom is enabled on the X-axis.
public boolean isZoomYEnabled()Checks whether zoom is enabled on the Y-axis.
public void setZoomLimits(double minRangeX, double maxRangeX, double minRangeY, double maxRangeY)Sets the zoom limits.
public void setZoomEnabled(boolean zoomX, boolean zoomY)Enables or disables zoom on x and y axes separately.
protected void chartBoundsChanged()Subclasses can override this method to be informed when the chart bounds change due to panning or zooming.

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, getDragRegionStatus, 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, resetFocusable, 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, getDragImage, getDragTransparency, setDragTransparency, toImage, dragInitiated, drawDraggedImage, draggingOver, dragEnter, dragExit, drop, addPullToRefresh, setPullToRefresh, respondsToPointerEvents, pointerDragged, isStickyDrag, pointerPressed, isDragAndDropOperation, pointerReleased, longPointerPress, 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, refreshTheme, isDragActivated, getGridPosY, getGridPosX, animate, scrollRectToVisible, scrollRectToVisible, paintBorder, paintBorderBackground, isCellRenderer, setCellRenderer, isScrollVisible, setScrollVisible, setIsScrollVisible, startEditingAsync, stopEditing, isEditing, isEditable, laidOut, deinitialize, initComponent, isInitialized, setInitialized, styleChanged, getNextFocusDown, setNextFocusDown, getNextFocusUp, setNextFocusUp, getNextFocusLeft, setNextFocusLeft, getNextFocusRight, setNextFocusRight, isEnabled, setEnabled, getName, setName, initCustomStyle, deinitializeCustomStyle, isRTL, setRTL, isTactileTouch, isTactileTouch, setTactileTouch, getPropertyNames, getPropertyTypes, getPropertyTypeNames, getPropertyValue, setPropertyValue, 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, getComponentState, setComponentState, setHidden, isHidden, setHidden, isHidden, announceForAccessibility, getAccessibilityText, setAccessibilityText, getSemantics, getAccessibilityNode, accessibilityChanged, accessibilityChanged, getTooltip, setTooltip

Constructor details

ChartComponent

public ChartComponent(AbstractChart chart)
Creates a new chart component to display the provided chart.

Parameters

chart AbstractChart
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.

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

paint

public void paint(Graphics g)
Paints the chart.

screenToChartCoord

public Point screenToChartCoord(int x, int y)
Converts screen coordinates to chart coordinates.

Parameters

x int
screen x position
y int
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 int
the x position within the chart
y int
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
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
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 Shape
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 Shape
The shape that should be shown.
duration int
The duration of the transition.

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 double
The lower bound of the X-axis after zoom.
maxX double
The upper bound of the X-axis after zoom.
minY double
The lower bound of the Y-axis after zoom.
maxY double
THe upper bound of the Y-axis after zoom.
duration int
Transition time (ms).

pointerPressed

public void pointerPressed(int x, int y)
If this Component is focused, the pointer pressed event will call this method

Parameters

x int
the pointer x coordinate
y int
the pointer y coordinate

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.

pointerReleased

public void pointerReleased(int x, int y)
If this Component is focused, the pointer released event will call this method

Parameters

x int
the pointer x coordinate
y int
the pointer y coordinate

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.

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 Transform
the transform to set

pointerDragged

public void pointerDragged(int[] x, int[] y)
If this Component is focused, the pointer dragged event will call this method

Parameters

x int[]
the pointer x coordinate
y int[]
the pointer y coordinate

isPanEnabled

public boolean isPanEnabled()
Checks if panning is enabled.

Returns

the panEnabled

setPanEnabled

public void setPanEnabled(boolean panEnabled)

Parameters

panEnabled boolean
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 boolean
True to enable panning along the x-axis.
panYEnabled boolean
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 double
The minimum X-axis value for panning.
maxX double
The maximum X-axis value for panning.
minY double
The minimum Y-axis value for panning.
maxY double
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 boolean
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 double
The minimum distance from XYMultipleSeriesRenderer#getXAxisMin() to XYMultipleSeriesRenderer#getXAxisMax() that can be achieved by zooming in. 0 means no limit.
maxRangeX double
The maximum distance from XYMultipleSeriesRenderer#getXAxisMin() to XYMultipleSeriesRenderer#getXAxisMax() that can be achieved by zooming out. 0 means no limit.
minRangeY double
The minimum distance from XYMultipleSeriesRenderer#getYAxisMin() to XYMultipleSeriesRenderer#getYAxisMax() that can be achieved by zooming in. 0 means no limit.
maxRangeY double
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 boolean
True to enable zooming x axis.
zoomY boolean
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.