Class GraphCanvas

All Implemented Interfaces:
javax.accessibility.Accessible, java.awt.event.ActionListener, java.util.EventListener, java.awt.image.ImageObserver, java.awt.MenuContainer, java.awt.print.Printable, java.io.Serializable

public class GraphCanvas
extends javax.swing.JPanel
implements java.awt.print.Printable, java.awt.event.ActionListener

Groovy graphing component.

See Also:
Serialized Form

Inner classes inherited from class javax.swing.JPanel
Inner classes inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent, javax.swing.JComponent.ActionStandin, javax.swing.JComponent.IntVector, javax.swing.JComponent.KeyboardState
Inner classes inherited from class java.awt.Container
Inner classes inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.AWTTreeLock
Field Summary
(package private)  javax.swing.border.TitledBorder decoration
          Decoration of the border of this frame.
private static int[] div_candidates
          Short list of nice groups to divide graph by.
(package private)  java.awt.Color frameColor
          The color of the exterior border.
(package private)  java.awt.Color gridColor
          The color of the grid lines.
private static double Log10
          Log base e of 10.
private static double Log10_2
          Log base 10 of 2.
private static double Log10_5
          Log base 10 of 5.
(package private)  java.util.Vector xyPairs
          A Vector of (Point2D.Double) xy-pairs to be graphed.
Fields inherited from class javax.swing.JPanel
defaultLayout, uiClassID
Fields inherited from class javax.swing.JComponent
_bounds, accessibleContext, actionMap, ACTIONMAP_CREATED, alignmentX, alignmentY, ANCESTOR_INPUTMAP_CREATED, ANCESTOR_USING_BUFFER, ancestorInputMap, ancestorNotifier, autoscroller, border, changeSupport, clientProperties, CREATED_DOUBLE_BUFFER, flags, FOCUS_INPUTMAP_CREATED, focusInputMap, HAS_FOCUS, htmlKey, htmlView, inputVerifier, IS_DOUBLE_BUFFERED, IS_OPAQUE, IS_PAINTING_TILE, IS_PRINTING, IS_PRINTING_ALL, KEY_EVENTS_ENABLED, KEYBOARD_BINDINGS_KEY, listenerList, maximumSize, minimumSize, NEXT_FOCUS, paintImmediatelyClip, paintingChild, preferredSize, readObjectCallbacks, REQUEST_FOCUS_DISABLED, tmpRect, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, verifyInputWhenFocusTarget, vetoableChangeSupport, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW, WHEN_IN_FOCUSED_WINDOW_BINDINGS, WIF_INPUTMAP_CREATED, windowInputMap
Fields inherited from class java.awt.Container
component, containerListener, containerSerializedDataVersion, dbg, dispatcher, layoutMgr, listeningBoundsChildren, listeningChildren, maxSize, ncomponents, printing, printingThreads, serialVersionUID
Fields inherited from class java.awt.Component
actionListenerK, adjustmentListenerK, appContext, background, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, componentListener, componentListenerK, componentOrientation, componentSerializedDataVersion, containerListenerK, cursor, dropTarget, enabled, eventMask, focusListener, focusListenerK, font, foreground, graphicsConfig, hasFocus, height, hierarchyBoundsListener, hierarchyBoundsListenerK, hierarchyListener, hierarchyListenerK, incRate, inputMethodListener, inputMethodListenerK, isInc, isPacked, itemListenerK, keyListener, keyListenerK, LEFT_ALIGNMENT, locale, LOCK, metrics, minSize, mouseListener, mouseListenerK, mouseMotionListener, mouseMotionListenerK, name, nameExplicitlySet, newEventsOnly, ownedWindowK, parent, peer, peerFont, popups, prefSize, privateKey, RIGHT_ALIGNMENT, textListenerK, TOP_ALIGNMENT, valid, visible, width, windowClosingException, windowListenerK, x, y
Fields inherited from interface java.awt.print.Printable
Fields inherited from interface java.awt.image.ImageObserver
Constructor Summary
          Bean-like constructor of a new graph.
Method Summary
 void actionPerformed(java.awt.event.ActionEvent e)
          Respond to a button press to self-print this panel.
 void addPoint(double x, double y)
          Add a point as two arguments.
 void addPoint(java.awt.geom.Point2D.Double p)
          Add a point as an ordered pair of doubles.
private static double chooseScale(double lo, double hi)
          AI routine to beautify the graph.
 void clearPoints()
          Clear all points on this graph.
private static double errorFromInt(double x)
          Given a fractional number near an integer, compute how far it is from the nearest integer.
 java.util.Vector getAllPoints()
          Get the actual handle to the points.
 java.awt.Color getFrameColor()
          Fetch the Color of the exterior plot frame.
 java.awt.Color getGridColor()
          Fetch the Color of the interior grid.
 java.lang.String getTitle()
          The title of the graph is printed.
static void main(java.lang.String[] ignored)
          Sample application.
 void paintComponent(java.awt.Graphics g)
          Nice paint routine for JComponents.
 void paintToScale(java.awt.Graphics g, java.awt.Dimension d, java.awt.Insets i)
          Routine to do most of the work of paintComponent() when the interior scales to the size of the printed page.
 int print(java.awt.Graphics g, java.awt.print.PageFormat pf, int pi)
          Print the graph on a single page of paper.
 void setAllPoints(java.util.Vector v)
          Load the graph with a new set of data.
 void setFrameColor(java.awt.Color c)
          Set the Color of the exterior plot frame.
 void setGridColor(java.awt.Color c)
          Set the Color of the interior grid.
 void setTitle(java.lang.String s)
          The title of the graph is printed.
Methods inherited from class javax.swing.JPanel
, getAccessibleContext, getUIClassID, paramString, updateUI, writeObject
Methods inherited from class javax.swing.JComponent
_paintImmediately, addAncestorListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, adjustPaintFlags, alwaysOnTop, checkIfChildObscuredBySibling, clearFocusOwners, componentInputMapChanged, computeVisibleRect, computeVisibleRect, compWriteObjectNotify, contains, createToolTip, disable, enable, enableSerialization, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getActionMap, getAlignmentX, getAlignmentY, getAutoscrolls, getBorder, getBounds, getClientProperties, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getCreatedDoubleBuffer, getDebugGraphicsOptions, getFlag, getGraphics, getHeight, getInputMap, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getVerifyInputWhenFocusTarget, getVisibleRect, getWidth, getX, getY, grabFocus, hasFocus, hide, isDoubleBuffered, isFocusCycleRoot, isFocusTraversable, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, paintWithBuffer, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processFocusEvent, processKeyBinding, processKeyBindings, processKeyBindingsForAllComponents, processKeyEvent, processMouseMotionEvent, putClientProperty, readObject, rectangleIsObscured, rectangleIsObscuredBySibling, registerKeyboardAction, registerKeyboardAction, registerWithKeyboardManager, registerWithKeyboardManager, removeAncestorListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setCreatedDoubleBuffer, setDebugGraphicsOptions, setDoubleBuffered, setEnabled, setFlag, setFont, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPaintingChild, setPreferredSize, setRequestFocusEnabled, setToolTipText, setUI, setVerifyInputWhenFocusTarget, setVisible, shouldDebugGraphics, superProcessMouseMotionEvent, unregisterKeyboardAction, unregisterWithKeyboardManager, unregisterWithKeyboardManager, update
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, adjustListeningChildren, applyOrientation, checkGD, countComponents, createChildHierarchyEvents, createHierarchyEvents, deliverEvent, dispatchEventImpl, dispatchEventToSelf, doLayout, eventEnabled, findComponentAt, findComponentAt, findComponentAt, getAccessibleAt, getAccessibleChild, getAccessibleChildrenCount, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents_NoClientCode, getComponents, getLayout, getMouseEventTarget, getWindow, initIDs, insets, invalidate, invalidateTree, isAncestorOf, layout, lightweightPaint, lightweightPrint, list, list, locate, minimumSize, nextFocus, numListening, paintComponents, paintHeavyweightComponents, postProcessKeyEvent, postsOldMouseEvents, preferredSize, preProcessKeyEvent, printComponents, printHeavyweightComponents, processContainerEvent, processEvent, proxyEnableEvents, proxyRequestFocus, remove, remove, removeAll, removeContainerListener, setFocusOwner, setLayout, transferFocus, validate, validateTree
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, areInputMethodsEnabled, bounds, checkImage, checkImage, checkWindowClosingException, coalesceEvents, constructComponentName, contains, createImage, createImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, getAccessibleIndexInParent, getAccessibleStateSet, getBackground, getBounds, getColorModel, getComponentOrientation, getCursor, getDropTarget, getFont_NoClientCode, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getInputContext, getInputMethodRequests, getLocale, getLocation, getLocationOnScreen_NoTreeLock, getLocationOnScreen, getName, getNativeContainer, getParent_NoClientCode, getParent, getPeer, getSize, getToolkit, getToolkitImpl, getTreeLock, getWindowForObject, gotFocus, handleEvent, imageUpdate, inside, isDisplayable, isEnabled, isEnabledImpl, isLightweight, isRecursivelyVisible, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, repaint, repaint, repaint, resetGC, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, registerNatives, wait, wait, wait

Field Detail


java.util.Vector xyPairs
A Vector of (Point2D.Double) xy-pairs to be graphed.


java.awt.Color gridColor
The color of the grid lines.


java.awt.Color frameColor
The color of the exterior border.


private static final double Log10
Log base e of 10. Used to convert log base e to log base 10.


private static final double Log10_2
Log base 10 of 2.


private static final double Log10_5
Log base 10 of 5.


javax.swing.border.TitledBorder decoration
Decoration of the border of this frame.


private static int[] div_candidates
Short list of nice groups to divide graph by.
Constructor Detail


public GraphCanvas()
Bean-like constructor of a new graph.
Method Detail


public void setTitle(java.lang.String s)
The title of the graph is printed.


public java.lang.String getTitle()
The title of the graph is printed.


public void addPoint(java.awt.geom.Point2D.Double p)
Add a point as an ordered pair of doubles.
p - A ordered pair on the coordinate plane, (x,y), for example.


public void addPoint(double x,
                     double y)
Add a point as two arguments.
x - The Abscissa.
y - The Ordinate.


public void clearPoints()
Clear all points on this graph.


public java.util.Vector getAllPoints()
Get the actual handle to the points.

Warning: Use of this Vector in a non-readonly manner is not recommended.


public void setAllPoints(java.util.Vector v)
Load the graph with a new set of data. Not Recommended to be used.
v - A Vector of Point2D.Doubles s.


public java.awt.Color getFrameColor()
Fetch the Color of the exterior plot frame.


public void setFrameColor(java.awt.Color c)
Set the Color of the exterior plot frame.
c - A color which should contrast with the background.


public java.awt.Color getGridColor()
Fetch the Color of the interior grid. This grid is automatically determined and labeled by an AI routine.


public void setGridColor(java.awt.Color c)
Set the Color of the interior grid. This should be a color that is distinct from the foreground.
c - A color, like Color.cyan, that reminds one of graph paper.


public void paintComponent(java.awt.Graphics g)
Nice paint routine for JComponents.
paintComponent in class javax.swing.JComponent


public void paintToScale(java.awt.Graphics g,
                         java.awt.Dimension d,
                         java.awt.Insets i)
Routine to do most of the work of paintComponent() when the interior scales to the size of the printed page.
g - A Graphics context in which to draw.
d - The apparent size of the Graphics object, g.
i - Defines a border (page margin) where we refrain from drawing.


private static double errorFromInt(double x)
Given a fractional number near an integer, compute how far it is from the nearest integer.
x - A fractional number like 1.8 or -3.3.


private static double chooseScale(double lo,
                                  double hi)
AI routine to beautify the graph.

Theory: Given a interval between low and high values, the prettiest division is between 3 and 10 pieces. To make sense, the divisions should correspond to a number that is in a human sense, round. This is a number like one of the set { 1, 2, 5 } times a power of ten. Experimentally, we can divide up the interval into 3 or more pieces and see which of the divisions comes closest to a round number.

If the interval includes zero as an interior number, we would also like to maximize the probability that our graph puts a grid line directly on zero.

lo - The lower bound of the interval.
hi - The higher bound of the interval.


public int print(java.awt.Graphics g,
                 java.awt.print.PageFormat pf,
                 int pi)
          throws java.awt.print.PrinterException
Print the graph on a single page of paper.
Specified by:
print in interface java.awt.print.Printable
g - PrintGraphics or Graphics2D.
pf - Details about the page layout.
pi - Index of the page to print.


public void actionPerformed(java.awt.event.ActionEvent e)
Respond to a button press to self-print this panel.
Specified by:
actionPerformed in interface java.awt.event.ActionListener
e - An Action which per think came from our print button.


public static void main(java.lang.String[] ignored)
Sample application.