Class Chart

java.lang.Object
com.codename1.ui.Component
com.codename1.ui.chart.Chart
All Implemented Interfaces:
Animation, Editable, StyleListener

public class Chart extends Component

An interactive, animated chart.

Form form = new Form("Revenue", new BorderLayout());
Chart chart = new Chart()
        .setXAxis(new CategoryAxis(Axis.BOTTOM, "Q1", "Q2", "Q3", "Q4"))
        .setTitle("Revenue");
chart.addSeries(new BarSeries("2025").setValues(12, 18, 9, 22));
chart.addSeries(new LineSeries("Target").setDashed(true).setValues(15, 15, 15, 15));
form.add(BorderLayout.CENTER, chart);

Layout is automatic: the chart measures every label before it draws, picks as many round-number ticks as fit, thins and shortens category labels that would collide and sizes the plot to whatever space is left. Data labels go through a collision layout and are dropped rather than drawn over each other.

Interaction works the same with touch, mouse, trackpad and keyboard: drag to pan once zoomed, pinch or scroll to zoom (spreading the fingers horizontally zooms only the x axis), double tap to zoom in and double tap again to reset, tap or hover a point for its tooltip, and tap a legend entry to hide or show its series. Data changes animate.

Style the component with the Chart UIID; its padding surrounds the plot, its font is the label font and its background shows through. Colours come from ChartTheme.

The parts of a chart

  • Field Details

    • LEGEND_NONE

      public static final int LEGEND_NONE
      No legend.
      See Also:
    • LEGEND_TOP

      public static final int LEGEND_TOP
      Legend above the plot.
      See Also:
    • LEGEND_BOTTOM

      public static final int LEGEND_BOTTOM
      Legend below the plot.
      See Also:
    • LEGEND_RIGHT

      public static final int LEGEND_RIGHT
      Legend right of the plot.
      See Also:
    • TOOLTIP_NONE

      public static final int TOOLTIP_NONE
      No tooltip.
      See Also:
    • TOOLTIP_POINT

      public static final int TOOLTIP_POINT
      Tooltip for the single point under the finger or pointer.
      See Also:
    • TOOLTIP_SHARED

      public static final int TOOLTIP_SHARED
      Tooltip listing every series at the x nearest the finger or pointer, with a crosshair.
      See Also:
    • ZOOM_AUTO

      public static final int ZOOM_AUTO
      Zoom gestures scale the value axis too unless the x axis is a category or time axis.
      See Also:
    • ZOOM_X

      public static final int ZOOM_X
      Zoom gestures scale the x (category) axis only; values keep their scale.
      See Also:
    • ZOOM_XY

      public static final int ZOOM_XY
      Zoom gestures scale both axes, following the direction of a pinch.
      See Also:
  • Constructor Details

    • Chart

      public Chart()
      Creates an empty chart with numeric axes.
  • Method Details

    • addSeries

      public Chart addSeries(Series s)
      Adds a series, animating it in when the chart is showing.
    • removeSeries

      public Chart removeSeries(Series s)
      Removes a series.
    • clearSeries

      public Chart clearSeries()
      Removes every series.
    • getSeries

      public List<Series> getSeries()
      The series, in paint order.
    • indexOf

      public int indexOf(Series s)
      The position of a series, which also selects its default palette colour.
    • addAnnotation

      public Chart addAnnotation(Annotation a)
      Adds a reference line, band or marker.
    • removeAnnotation

      public Chart removeAnnotation(Annotation a)
      Removes an annotation.
    • update

      public void update(Runnable changes)
      Runs several data changes as one animated transition.
    • getXAxis

      public Axis getXAxis()
      The x (category) axis.
    • setXAxis

      public Chart setXAxis(Axis a)
      Replaces the x axis, for example with a CategoryAxis or TimeAxis.
    • getYAxis

      public Axis getYAxis()
      The primary value axis.
    • setYAxis

      public Chart setYAxis(Axis a)
      Replaces the primary value axis, for example with a LogAxis.
    • getSecondaryYAxis

      public Axis getSecondaryYAxis()
      The secondary value axis on the right, or null.
    • setSecondaryYAxis

      public Chart setSecondaryYAxis(Axis a)

      Adds a right hand value axis for series with setSecondaryAxis(true).

      A rotated chart (setRotated(true)) has no room for a second horizontal value axis, so while it is rotated the secondary axis is neither laid out nor painted and its series and annotations are measured against the primary value axis instead.

    • getTheme

      public ChartTheme getTheme()
      The colour theme.
    • refreshTheme

      protected void refreshTheme(String id, boolean merge)
      Description copied from class: Component

      Makes sure the component is up to date with the given UIID

      Parameters
      • id: The Style Id to update the Component with

      • merge: indicates if the current styles should be merged with the new styles

      Overrides:
      refreshTheme in class Component
    • styleChanged

      public void styleChanged(String propertyName, Style source)
      Description copied from class: Component

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

      public Chart setTheme(ChartTheme theme)
      Replaces the colour theme.
    • getTitle

      public String getTitle()
      The chart title, or null.
    • setTitle

      public Chart setTitle(String title)
      Sets a title drawn above the plot.
    • setLegendPosition

      public Chart setLegendPosition(int pos)
      One of the LEGEND_ constants. The default is below the plot; a chart with a single series and no pie hides its legend automatically.
    • setTooltipMode

      public Chart setTooltipMode(int mode)
      One of the TOOLTIP_ constants.
    • setTooltipRenderer

      public Chart setTooltipRenderer(TooltipRenderer r)
      Customizes the tooltip's rows.
    • isRotated

      public boolean isRotated()
      True for a horizontal bar chart: the x (category) axis runs down the left side.
    • setRotated

      public Chart setRotated(boolean rotated)
      Swaps the axes so categories run vertically and values horizontally.
    • setZoomEnabled

      public Chart setZoomEnabled(boolean zoomEnabled)
      Whether pinch, wheel, double tap and drag zoom and pan the chart.
    • setZoomMode

      public Chart setZoomMode(int zoomMode)
      Which axes pinch, wheel, double tap and keyboard zoom: ZOOM_AUTO (the default), ZOOM_X or ZOOM_XY.
    • getZoomMode

      public int getZoomMode()
      One of the ZOOM_ constants.
    • setAnimationDuration

      public Chart setAnimationDuration(int ms)
      Transition length in milliseconds; 0 applies data changes without animating.
    • setLoading

      public Chart setLoading(String text)

      Shows that data is on its way: with no data yet the text replaces the empty state, and over existing data the chart is dimmed under it. It stays until setLoading(null), so a caller that loads in steps decides when the data is complete.

      Parameters
      • text: the text to show, or null to stop showing it
      Returns

      this chart

    • isLoading

      public boolean isLoading()
      Whether setLoading is showing a loading state.
    • setBrushEnabled

      public Chart setBrushEnabled(boolean enabled)

      Makes a drag inside the plot select a range of x values instead of scrubbing or panning; pinch, the wheel and the keyboard still zoom and pan. The selection is reported to addRangeListener and, unless setBrushZooms(false), the chart zooms to it. While the chart is zoomed a one finger drag pans instead, so a zoomed chart stays reachable by touch; resetting the zoom brings the brush back.

      Parameters
      • enabled: true to brush
      Returns

      this chart

    • setBrushZooms

      public Chart setBrushZooms(boolean zooms)

      Whether a brush selection also zooms the chart to it; true by default.

      Parameters
      • zooms: false to only report the selection
      Returns

      this chart

    • addRangeListener

      public void addRangeListener(RangeListener l)
      Adds a listener for brush selections.
    • removeRangeListener

      public void removeRangeListener(RangeListener l)
      Removes a brush selection listener.
    • setEmptyText

      public Chart setEmptyText(String text)
      Text shown when there is nothing to plot.
    • addSelectionListener

      public void addSelectionListener(SelectionListener l)
      Listens for taps on data points.
    • removeSelectionListener

      public void removeSelectionListener(SelectionListener l)
      Stops listening.
    • setSelection

      public Chart setSelection(Series s, int index)
      Selects point index of s and shows its tooltip, as a tap on it would; null clears the selection. Arrow-key stepping continues from the point, and the screen reader announces it. Selection listeners are not called: they report the user's taps and keys, and the caller already knows what it selected. Before the chart is first painted the selection is kept and applied by that paint.
    • showTooltipAtX

      public Chart showTooltipAtX(double x)
      Shows the shared tooltip and crosshair at data x x, as a tap there would in TOOLTIP_SHARED mode; linked charts follow. Does nothing in other modes.
    • getTooltipX

      public double getTooltipX()
      The data x the shared tooltip shows, or NaN when it shows none.
    • setLegendToggles

      public Chart setLegendToggles(boolean toggles)
      Whether tapping a legend entry hides and shows its series (the default). Legend listeners are told of taps either way.
    • isLegendToggles

      public boolean isLegendToggles()
      Whether tapping a legend entry hides and shows its series.
    • addLegendListener

      public void addLegendListener(LegendListener l)
      Listens for taps on legend entries.
    • removeLegendListener

      public void removeLegendListener(LegendListener l)
      Stops listening.
    • getSelection

      public ChartPoint getSelection()
      The selected point, or null.
    • getLastContext

      public ChartContext getLastContext()
      The frame last painted; hit testing and transitions read its geometry.
    • toImage

      public Image toImage(int width, int height)
      Renders the chart into an image, for sharing or export.
    • beginChange

      public void beginChange()
      Snapshots what is on screen as the start of the next transition. Called by series before they mutate; applications use update(Runnable) instead.
    • initComponent

      protected void initComponent()
      Description copied from class: Component
      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()
      Description copied from class: Component
      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
    • animate

      public boolean animate()
      Description copied from class: Component

      Allows the animation to reduce "repaint" calls when it returns false. It is called once for every frame. Frames are defined by the com.codename1.ui.Display class.

      Returns

      true if a repaint is desired or false if no repaint is necessary

      Specified by:
      animate in interface Animation
      Overrides:
      animate in class Component
    • 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)
      Description copied from class: Component

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

      public List<String[]> getTableRows()

      The chart's data as rows of {series, item, value}, in series order. Hidden series are included: the table is the complete data, not what happens to be on screen. A gap has no value and no row.

      Returns

      a new list of rows

    • toTableModel

      public TableModel toTableModel()

      The chart's data as a table model with the columns Series, Item and Value, for a data table view, export, or a screen reader friendly alternative to the picture.

      Returns

      a new, read only table model

    • toTable

      public Table toTable()

      A table component showing the chart's data; offer it beside or instead of the chart for readers who cannot see it.

      Returns

      a new table

    • describe

      public String describe()

      A one paragraph summary of the chart for screen readers: its title and, for each series, how many values it has and their range.

      Returns

      the summary

    • getAccessibilityText

      public String getAccessibilityText()
      The accessibility text set on the chart, or a generated summary of its data.
      Overrides:
      getAccessibilityText in class Component
    • hitTest

      public ChartPoint hitTest(int x, int y)
      Finds the point at a chart relative position, the topmost series first.
    • 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
    • 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
    • pinchReleased

      protected void pinchReleased(int x, int y)
      Description copied from class: Component

      To be implemented by subclasses interested in being notified when a pinch zoom has ended (i.e the user has removed one of their fingers, but is still dragging).

      Parameters
      • x: The x-coordinate of the remaining finger in the drag. (Absolute)

      • y: The y-coordinate of the remaining finger in the drag. (Absolute)

      Overrides:
      pinchReleased in class Component
    • 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
    • resetZoom

      public void resetZoom()
      Returns to the full data range with an animation.
    • mouseWheel

      protected boolean mouseWheel(WheelEvent ev)
      Description copied from class: Component

      Handles a scroll wheel or trackpad scroll over this component, before its listeners and before anything above it in the hierarchy.

      A component that moves its own content -- an editor that scrolls itself, a viewer that pans -- implements this. Everything else leaves it alone and the wheel scrolls the nearest scrollable ancestor, which is what a wheel means.

      This exists because a wheel used to arrive as a synthetic press, drag and release played into the component tree: a component that wanted the wheel got it by handling pointer events, and so did every component that did not want it. The events are gone and this is what replaces them, for the few components that have something of their own to move.

      Parameters
      • ev: the wheel event, carrying the scroll deltas in display pixels
      Returns

      true when this component handled the wheel and nothing else should act on it

      Overrides:
      mouseWheel in class Component
    • pointerHover

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

      Invoked for devices where the pointer can hover without actually clicking the display. This is true for PC mouse pointer as well as some devices such as the BB storm.

      Parameters
      • x: the pointer x coordinate

      • y: the pointer y coordinate

      Overrides:
      pointerHover in class Component
    • pointerHoverReleased

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

      Invoked for devices where the pointer can hover without actually clicking the display. This is true for PC mouse pointer as well as some devices such as the BB storm.

      Parameters
      • x: the pointer x coordinate

      • y: the pointer y coordinate

      Overrides:
      pointerHoverReleased in class Component
    • keyReleased

      public void keyReleased(int keyCode)
      Description copied from class: Component

      If this Component is focused, the key released event will call this method

      Parameters
      • keyCode: the key code value to indicate a physical key.
      Overrides:
      keyReleased in class Component
    • syncWith

      public void syncWith(Chart other)
      Links this chart's x axis viewport and crosshair with other charts, as a price chart and its volume or indicator panes need: panning or zooming one pans the others.
    • unsync

      public void unsync()
      Leaves the group joined with syncWith: this chart stops following the others and they stop following it, while the rest of the group stays linked. Removing a chart from its form does not unlink it, so a chart shown again keeps syncing; call this when a linked chart is discarded.