public class 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,ChartComponentclass includes optional pinch zoom support.Panning Support - The
com.codename1.charts,ChartComponentclass 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.modelspackage. 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.rendererspackage. 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.viewspackage.**Create a
com.codename1.charts,ChartComponent**. In order to add your chart to the UI, you need to wrap it in acom.codename1.charts,ChartComponentobject.
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
Inherited fields
From Component
DEFAULT_CURSOR, CROSSHAIR_CURSOR, TEXT_CURSOR, WAIT_CURSOR, SW_RESIZE_CURSOR, SE_RESIZE_CURSOR, NW_RESIZE_CURSOR, NE_RESIZE_CURSOR, N_RESIZE_CURSOR, S_RESIZE_CURSOR, W_RESIZE_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, MOVE_CURSOR, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_Y, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_IMMEDIATELY_DRAG_XY, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_CENTER_OFFSET, BRB_OTHER, CENTER, TOP, LEFT, BOTTOM, RIGHT, BASELINE
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)Parameters
chartAbstractChart- The chart to be displayed in this component.
Method details
getChart
public AbstractChart getChart()setChart
public void setChart(AbstractChart chart)calcPreferredSize
protected Dimension calcPreferredSize()Returns
paint
public void paint(Graphics g)screenToChartCoord
public Point screenToChartCoord(int x, int y)Parameters
xint- screen x position
yint- screen y position
Returns
chartToScreenCoord
public Point chartToScreenCoord(int x, int y)Parameters
xint- the x position within the chart
yint- the y position within the chart
Returns
screenToChartShape
public Shape screenToChartShape(Shape s)Parameters
sShape- shape in screen coordinates
Returns
chartToScreenShape
public Shape chartToScreenShape(Shape s)Parameters
sShape- shape in chart coordinates
Returns
zoomToShapeInChartCoords
public void zoomToShapeInChartCoords(Shape s)Parameters
sShape- The shape that should be shown.
zoomToShapeInChartCoords
public void zoomToShapeInChartCoords(Shape s, int duration)Parameters
sShape- The shape that should be shown.
durationint- The duration of the transition.
zoomTo
public void zoomTo(double minX, double maxX, double minY, double maxY, int duration)int) except
it allows you to specify coordinates as doubles.Parameters
minXdouble- The lower bound of the X-axis after zoom.
maxXdouble- The upper bound of the X-axis after zoom.
minYdouble- The lower bound of the Y-axis after zoom.
maxYdouble- THe upper bound of the Y-axis after zoom.
durationint- Transition time (ms).
pointerPressed
public void pointerPressed(int x, int y)Parameters
xint- the pointer x coordinate
yint- the pointer y coordinate
seriesPressed
protected void seriesPressed(SeriesSelection sel)pointerReleased
public void pointerReleased(int x, int y)Parameters
xint- the pointer x coordinate
yint- the pointer y coordinate
seriesReleased
protected void seriesReleased(SeriesSelection sel)getTransform
public Transform getTransform()Returns
setTransform
public void setTransform(Transform transform)Parameters
transformTransform- the transform to set
pointerDragged
public void pointerDragged(int[] x, int[] y)Parameters
xint[]- the pointer x coordinate
yint[]- the pointer y coordinate
isPanEnabled
public boolean isPanEnabled()Returns
setPanEnabled
public void setPanEnabled(boolean panEnabled)Parameters
panEnabledboolean- the panEnabled to set
setPanEnabled
public void setPanEnabled(boolean panXEnabled, boolean panYEnabled)setPanEnabled(true, false) lets the user pan left/right but pins the
Y axis (a useful pattern for time-series charts).Parameters
panXEnabledboolean- True to enable panning along the x-axis.
panYEnabledboolean- True to enable panning along the y-axis.
isPanXEnabled
public boolean isPanXEnabled()isPanYEnabled
public boolean isPanYEnabled()setPanLimits
public void setPanLimits(double minX, double maxX, double minY, double maxY)Parameters
minXdouble- The minimum X-axis value for panning.
maxXdouble- The maximum X-axis value for panning.
minYdouble- The minimum Y-axis value for panning.
maxYdouble- The maximum Y-axis value for panning.
clearPanLimits
public void clearPanLimits()double, double, double)isZoomEnabled
public boolean isZoomEnabled()Returns
setZoomEnabled
public void setZoomEnabled(boolean zoomEnabled)Parameters
zoomEnabledboolean- the zoomEnabled to set
isZoomXEnabled
public boolean isZoomXEnabled()isZoomYEnabled
public boolean isZoomYEnabled()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
minRangeXdouble- The minimum distance from
XYMultipleSeriesRenderer#getXAxisMin()toXYMultipleSeriesRenderer#getXAxisMax()that can be achieved by zooming in. 0 means no limit. maxRangeXdouble- The maximum distance from
XYMultipleSeriesRenderer#getXAxisMin()toXYMultipleSeriesRenderer#getXAxisMax()that can be achieved by zooming out. 0 means no limit. minRangeYdouble- The minimum distance from
XYMultipleSeriesRenderer#getYAxisMin()toXYMultipleSeriesRenderer#getYAxisMax()that can be achieved by zooming in. 0 means no limit. maxRangeYdouble- The maximum distance from
XYMultipleSeriesRenderer#getYAxisMin()toXYMultipleSeriesRenderer#getYAxisMax()that can be achieved by zooming out. 0 means no limit.
setZoomEnabled
public void setZoomEnabled(boolean zoomX, boolean zoomY)Parameters
zoomXboolean- True to enable zooming x axis.
zoomYboolean- True to enable zooming y axis.
chartBoundsChanged
protected void chartBoundsChanged()