org.formaria.swing
Class Graph

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by org.formaria.swing.Graph
All Implemented Interfaces:
java.awt.event.ActionListener, java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, ModelHolder

public class Graph
extends javax.swing.JComponent
implements java.awt.event.ActionListener, ModelHolder

An component that displays data as charts/graphs. The display can be Pie, Scatter, Line, X-Y or Bar charts

Copyright (c) Formaria Ltd., 2008, This software is licensed under the GNU Public License (GPL), please see license.txt for more details. If you make commercial use of this software you must purchase a commercial license from formaria.

$Revision: 1.29 $

See Also:
Serialized Form

Nested Class Summary
 class Graph.SelectableArea
          An area of the chart that can be selected, with information about that area
 
Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
 
Field Summary
static int BARCHART
          Bar chart - with one bar per value in each series
protected  Project currentProject
          The owner project and the context in which this object operates.
static int LABELS
          The labels column/field in the source data table
static int LINEAR
          Linear axis
static int LINECHART
          A simple line chart with connected points
static int LOGARITHMIC
          A Log10 axis
static int PIECHART
          A pie chart showing the first series
static int SCATTERCHART
          A plot with points for each x-y value pair
static int SERIES
          The series column/field in the source data table
static int STACKEDBARCHART
          Bar chart with the bars for each value in the series stacked upon one another so that there is one bar for each x value
static int VALUES
          The values column/field in the source data table
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
Graph()
          Construct a new graph/chart
 
Method Summary
 void actionPerformed(java.awt.event.ActionEvent e)
          An action handler for the animation timer
protected  java.awt.Color darken(java.awt.Color c, double degrees)
          Darken the selected color for the sides of the pie chart
 void drawBarChart(java.awt.Graphics2D g2d)
          Draw a simple bar chart
protected  void drawLegend(java.awt.Graphics2D g2d, double x, double y, double w, double h)
          Draw the chart legend
 void drawLineChart(java.awt.Graphics2D g2d)
          Draw a line chart
 void drawPieChart(java.awt.Graphics2D g2d)
          Draw a pie chart with the first data series
 void drawScale(java.awt.Graphics2D g2d, boolean isVertical)
          Draw a scale
 void drawSelectedArea(java.awt.Graphics2D g2d)
          Highlight the selected area - if any
 void drawStackedBarChart(java.awt.Graphics2D g2d)
          Draw a stacked bar chart
 boolean getDrawBorder()
          Get the drawBorder flag value
protected  java.awt.Color getGeneratedColor(int idx)
          Generate an HSB color, using the index as an offset int the H color range
protected  java.awt.Color getGeneratedColor(int i, int opacity)
          Get a generated color with partial opacity
 boolean getHighlight()
          Get the highlight flag value
protected  double getLabelHeight(java.awt.Graphics g)
          Get the height of the X axis labels
 boolean getLabels()
          Get the labels flag value
 int getLegendPos()
          Get the legend position
protected  int getLegendSpace(boolean verticalSpace)
          Get the space consumed by the legend
protected  int getLegendX(double left, double right)
          Get the legend x coordinate
protected  int getLegendY(double top, double bottom)
          Get the legend y coordinate
 boolean getMarkers()
          Get the markers flag value
 double getMaxY()
          Get the maximum Y value
 double getMinY()
          Get the minimum Y value
 int getMode()
          Get the current display mode of the chart
 Graph.SelectableArea getSelectableArea()
          Get the selectable area
 java.lang.String getTitle()
          Get the graph title
protected  double getYLabelWidth(java.awt.Graphics g)
          Get the height of the X axis labels
 void paintComponent(java.awt.Graphics g)
          Renders the chart image.
 void print(java.awt.Graphics g)
          Setup the envelope component for printing
 void setBorderStyle(boolean value)
           
 void setBounds(int x, int y, int w, int h)
          Set the bounds for this component and layout the children
 void setData(double[] pts, int nSeries, java.lang.String[] names, boolean animate)
          Set the chart data
 void setDataModel(DataModel xmodel)
          Set the DataModel which we will be generating the table from
 void setDrawBorder(boolean b)
          Set the drawBorder flag value
 void setHighlight(boolean b)
          Set the highlight flag value
 void setLabels(boolean b)
          Set the labels flag value
 void setLegendPos(int y)
          Set the legend position
 void setMarkers(boolean b)
          Set the markers flag value
 void setMaxY(double y)
          Set the maximum Y value
 void setMinY(double y)
          Set the minimum Y value
 void setMode(int newMode)
          Set the display mode of the chart
 void setModelStructure(int attribute, int value)
          Define the location of the data in the model
 void setTitle(java.lang.String newStr)
          Set the text of the form to the specified language string, the setLangString(...) function is the preferred method of setting the caption.
 void setXScale(double min, double max, int type, java.lang.String title, java.lang.String[] labels)
          Set the Scale options
 void setYScale(int type, java.lang.String title)
          Set the Scale options
 void toggleYAxisAnimation()
          Turn on/off the animation of new data
 void update()
          Force a repaint
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getAccessibleContext, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, paramString, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update, updateUI
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

BARCHART

public static final int BARCHART
Bar chart - with one bar per value in each series

See Also:
Constant Field Values

STACKEDBARCHART

public static final int STACKEDBARCHART
Bar chart with the bars for each value in the series stacked upon one another so that there is one bar for each x value

See Also:
Constant Field Values

LINECHART

public static final int LINECHART
A simple line chart with connected points

See Also:
Constant Field Values

PIECHART

public static final int PIECHART
A pie chart showing the first series

See Also:
Constant Field Values

SCATTERCHART

public static final int SCATTERCHART
A plot with points for each x-y value pair

See Also:
Constant Field Values

LINEAR

public static final int LINEAR
Linear axis

See Also:
Constant Field Values

LOGARITHMIC

public static final int LOGARITHMIC
A Log10 axis

See Also:
Constant Field Values

SERIES

public static final int SERIES
The series column/field in the source data table

See Also:
Constant Field Values

LABELS

public static final int LABELS
The labels column/field in the source data table

See Also:
Constant Field Values

VALUES

public static final int VALUES
The values column/field in the source data table

See Also:
Constant Field Values

currentProject

protected Project currentProject
The owner project and the context in which this object operates.

Constructor Detail

Graph

public Graph()
Construct a new graph/chart

Method Detail

setModelStructure

public void setModelStructure(int attribute,
                              int value)
Define the location of the data in the model

Parameters:
attribute - the attribute being defined (LABELS, SERIES, VALUES)
value - the column of field where that data can be found

getSelectableArea

public Graph.SelectableArea getSelectableArea()
Get the selectable area

Returns:
the selected area or null if there is no selection

actionPerformed

public void actionPerformed(java.awt.event.ActionEvent e)
An action handler for the animation timer

Specified by:
actionPerformed in interface java.awt.event.ActionListener
Parameters:
e - the event

setBounds

public void setBounds(int x,
                      int y,
                      int w,
                      int h)
Set the bounds for this component and layout the children

Overrides:
setBounds in class java.awt.Component
Parameters:
x - the x coordinate
y - the y coordinate
w - the width
h - the height

setXScale

public void setXScale(double min,
                      double max,
                      int type,
                      java.lang.String title,
                      java.lang.String[] labels)
Set the Scale options

Parameters:
min - the min value
max - the max value
type - the type of axis
title - the axis title
labels - the labels for the markers in the series

setYScale

public void setYScale(int type,
                      java.lang.String title)
Set the Scale options

Parameters:
type - the type of axis
title - the axis title

update

public void update()
Force a repaint

Specified by:
update in interface ModelHolder

setDataModel

public void setDataModel(DataModel xmodel)
Set the DataModel which we will be generating the table from

Specified by:
setDataModel in interface ModelHolder
Parameters:
xmodel - The DataModel of data

setData

public void setData(double[] pts,
                    int nSeries,
                    java.lang.String[] names,
                    boolean animate)
Set the chart data

Parameters:
nSeries - the number of series
pts - the data points in x, y pairs, a complete series at a time e.g. ax1, ay1, ax2, ay2, .... xn, yn, bx1, by1, bx2, by2
names - the names of the series
animate - true to animate new data

toggleYAxisAnimation

public void toggleYAxisAnimation()
Turn on/off the animation of new data


print

public void print(java.awt.Graphics g)
Setup the envelope component for printing

Overrides:
print in class javax.swing.JComponent
Parameters:
g - the graphics context

paintComponent

public void paintComponent(java.awt.Graphics g)
Renders the chart image.

Overrides:
paintComponent in class javax.swing.JComponent
Parameters:
g - the graphics context

drawScale

public void drawScale(java.awt.Graphics2D g2d,
                      boolean isVertical)
Draw a scale

Parameters:
g2d - the graphics context
isVertical - true to draw a vertical axis, otherwise the horizontal axis is drawn

drawBarChart

public void drawBarChart(java.awt.Graphics2D g2d)
Draw a simple bar chart

Parameters:
g2d - the graphics context

drawStackedBarChart

public void drawStackedBarChart(java.awt.Graphics2D g2d)
Draw a stacked bar chart

Parameters:
g2d - the graphics context

drawLineChart

public void drawLineChart(java.awt.Graphics2D g2d)
Draw a line chart

Parameters:
g2d - the graphics context

getLabelHeight

protected double getLabelHeight(java.awt.Graphics g)
Get the height of the X axis labels

Parameters:
g - the graphics context
Returns:
the label space height

getYLabelWidth

protected double getYLabelWidth(java.awt.Graphics g)
Get the height of the X axis labels

Parameters:
g - the graphics context
Returns:
the label space height

getLegendSpace

protected int getLegendSpace(boolean verticalSpace)
Get the space consumed by the legend

Parameters:
verticalSpace - true if the legend is shown horizontally below the chart
Returns:
the size the legend consumes if it does not overlap the chart area

getLegendX

protected int getLegendX(double left,
                         double right)
Get the legend x coordinate

Parameters:
left - the left edge of the chart
right - the right edge of the chart
Returns:
the starting x coordinate of the legend

getLegendY

protected int getLegendY(double top,
                         double bottom)
Get the legend y coordinate

Parameters:
top - the top edge of the chart
bottom - the bottom edge of the chart
Returns:
the starting y coordinate of the legend

drawLegend

protected void drawLegend(java.awt.Graphics2D g2d,
                          double x,
                          double y,
                          double w,
                          double h)
Draw the chart legend

Parameters:
g2d - the graphics context
x - the x/left position
y - the y/top position
w - the width
h - the height

getDrawBorder

public boolean getDrawBorder()
Get the drawBorder flag value

Returns:
true if the border is drawn

setDrawBorder

public void setDrawBorder(boolean b)
Set the drawBorder flag value

Parameters:
b - true if the border is drawn

getLabels

public boolean getLabels()
Get the labels flag value

Returns:
true if the border is drawn

setLabels

public void setLabels(boolean b)
Set the labels flag value

Parameters:
b - true if the lables are drawn on the data points

getHighlight

public boolean getHighlight()
Get the highlight flag value

Returns:
true if the current value is highlighted as the mouse is moved

setHighlight

public void setHighlight(boolean b)
Set the highlight flag value

Parameters:
b - true if the current value is to be highlighted as the mouse is moved

getMarkers

public boolean getMarkers()
Get the markers flag value

Returns:
true if the markers are drwan for each point

setMarkers

public void setMarkers(boolean b)
Set the markers flag value

Parameters:
b - true if the markers are drwan for each point

getMinY

public double getMinY()
Get the minimum Y value

Returns:
the minimum value

setMinY

public void setMinY(double y)
Set the minimum Y value

Parameters:
y - the minimum value

getMaxY

public double getMaxY()
Get the maximum Y value

Returns:
the maximum value

setMaxY

public void setMaxY(double y)
Set the maximum Y value

Parameters:
y - the maximum value

getLegendPos

public int getLegendPos()
Get the legend position

Returns:
the position value, 0=top left, 1=top right, 2=bottom left, 3=bottom right, 4=right margin, 5=bottom margin

setLegendPos

public void setLegendPos(int y)
Set the legend position

Parameters:
pos - value=the legend position, 0=top left, 1=top right, 2=bottom left, 3=bottom right, 4=right margin, 5=bottom margin

drawPieChart

public void drawPieChart(java.awt.Graphics2D g2d)
Draw a pie chart with the first data series

Parameters:
g2d - the graphics context

drawSelectedArea

public void drawSelectedArea(java.awt.Graphics2D g2d)
Highlight the selected area - if any

Parameters:
g2d - the graphics context

darken

protected java.awt.Color darken(java.awt.Color c,
                                double degrees)
Darken the selected color for the sides of the pie chart

Parameters:
c - the selected color
degrees - the angle/position at which the color is used
Returns:
the new color

getGeneratedColor

protected java.awt.Color getGeneratedColor(int idx)
Generate an HSB color, using the index as an offset int the H color range

Parameters:
idx - the index of the color
Returns:
the new color

getGeneratedColor

protected java.awt.Color getGeneratedColor(int i,
                                           int opacity)
Get a generated color with partial opacity

Parameters:
i - the color index
opacity - the opacity in the range 0-255
Returns:
the new color

setMode

public void setMode(int newMode)
Set the display mode of the chart

Parameters:
newMode - the new mode: 0=BAR, 1=STACKEDBAR, 2=LINE, 3=PIE, 4=SCATTER

getMode

public int getMode()
Get the current display mode of the chart

Returns:
the mode: 0=BAR, 1=STACKEDBAR, 2=LINE, 3=PIE, 4=SCATTER

setTitle

public void setTitle(java.lang.String newStr)
Set the text of the form to the specified language string, the setLangString(...) function is the preferred method of setting the caption.

Parameters:
newStr - the new title

getTitle

public java.lang.String getTitle()
Get the graph title

Returns:
the title text

setBorderStyle

public void setBorderStyle(boolean value)
Parameters:
value -