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.

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

      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.