Class PlotCanvas
- All Implemented Interfaces:
DataChangeListener,ImageObserver,MenuContainer,Serializable,EventListener
Responsibilities
- Owning the coordinate-system geometry (
_worldSystem,setWorldSystem(), affine transforms) - Painting: delegating to
DataDrawer,PlotTicks,Legend, andExtraText - Notifying
PlotChangeListeners on lifecycle events - Providing the public coordinate-conversion API (screen ↔ raw-world ↔ data)
- Data management:
setPlotData(edu.cnu.mdi.splot.pdata.PlotData),clearData()
Mouse handling
All mouse interaction (legend dragging, feedback readout, scroll-wheel
zoom) is delegated to PlotMouseHandler, which is wired up in the
constructor. PlotCanvas no longer implements any mouse listener
interfaces directly.
Coordinate systems
Three coordinate spaces are in play:
- Screen (local) — Swing pixel coordinates,
(0,0)at top-left. - Raw world — stored in
_worldSystem; log₁₀(data) when a log axis is active. - Data — the real values in the curves, always linear.
Conversion methods are named screen*, *RawWorld*, and
*Data* to make the direction explicit.
- Author:
- heddle
- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponentNested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainerNested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected PlotParametersVisual and numerical parameters (axis labels, fonts, log scale, etc.).protected PlotDataThe data backing this canvas.protected AffineTransformTransforms raw-world → screen (null when component has no valid size).protected AffineTransformTransforms screen → raw-world (null when component has no valid size).static final StringFired when the axes font changes.static final StringFired when the color map changes (2D histograms / heatmaps).static final StringFired after every completed paint pass.static final StringFired when log-Z mode changes (2D histograms).static final StringFired when the status/feedback font changes.static final StringFired when the plot title font changes.static final StringFired when the plot title text changes.static final StringFired when the x-axis label text changes.static final StringFired when the y-axis label text changes.Fields inherited from class javax.swing.JComponent
listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOWFields inherited from class java.awt.Component
accessibleContext, BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENTFields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH -
Constructor Summary
ConstructorsConstructorDescriptionPlotCanvas(PlotData plotData, String plotTitle, String xLabel, String yLabel) Creates aPlotCanvasfor the given dataset. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddPlotChangeListener(PlotChangeListener listener) Registers aPlotChangeListenerfor lifecycle events.voidClears all data from every curve.voiddataSetChanged(PlotData plotData, ACurve curve, CurveChangeType type) Called by the data model when curve data changes.dataToScreen(double dataX, double dataY) Converts a single data point to a screen point.dataToScreen(double dataX0, double dataY0, double dataX1, double dataY1) Converts a data rectangle specified by two corners to a screen rectangle.booleandataToScreen(Point screenPt, Point2D.Double dataPoint) Converts a data point (linear units) to screen (pixel) coordinates.booleandataToScreen(Rectangle screenRect, Rectangle2D.Double dataRect) Converts a data rectangle (linear units) to a screen rectangle.Returns the pixel bounds of the active (data) area within the component.Returns the visible region in data (linear) coordinates.Returns the plot parameters object.Returns the dataset backing this canvas.Returns the tick-mark renderer for this canvas.getTitle()Returns the plot title.getType()Returns the currentPlotDataType.getWorld()Returns the visible region in raw-world coordinates.booleanReturnstrueif this canvas is configured as a bar plot.booleanReturnstrueif log-10 scaling is active on the x-axis.booleanReturnstrueif log-10 scaling is active on the y-axis.voidneedsRedraw(boolean rescale) Signals that this canvas needs a repaint, optionally requesting a world rescale.voidPaints the canvas: background, data, frame, ticks, legend, extra text.Returns thePlotPanelthat contains this canvas, if any.voidremoteFirePropertyChange(String propName, Object oldValue, Object newValue) Triggers a property-change event on behalf of another object (e.g.voidvoidremovePlotChangeListener(PlotChangeListener listener) Removes a previously registeredPlotChangeListener.voidscale(double amount) Scales the visible area byamountaround its center.voidscreenToData(Point screenPoint, Point2D.Double dataPoint) Converts a screen (pixel) point to data coordinates (always linear units).voidscreenToData(Rectangle screenRect, Rectangle2D.Double dataRect) Converts a screen rectangle to data-space bounds (always linear units).voidscreenToRawWorld(Point screenPoint, Point2D.Double rawPoint) Converts a screen (pixel) point to raw-world coordinates.voidscreenToRawWorld(Rectangle screenRect, Rectangle2D.Double rawRect) Converts a screen (pixel) rectangle to a raw-world rectangle.protected voidRebuilds the affine transforms from the current world system and active bounds.voidSets the optional parent component (usually aPlotPanel).protected voidsetPlotData(PlotData plotData) Replaces the dataset and recomputes the world system.voidsetToolBar(BaseToolBar toolBar) Sets the toolbar that owns this canvas.voidRecomputes the world system from the current data and plot parameters.voidOpens the plot preferences dialog.voidshutDown()Stops the timer and notifies listeners that the canvas is shutting down.voidstandUp()Starts the timer and notifies listeners that the canvas is active.voidzoomToRect(Rectangle rbrect) Zooms to a rubber-band rectangle specified in screen (pixel) coordinates.Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, 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, getUI, getUIClassID, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, paramString, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, 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, updateUIMethods 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, transferFocusDownCycle, validate, validateTreeMethods 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, getAccessibleContext, 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, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, 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, requestFocus, requestFocus, requestFocusInWindow, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setMixingCutoutShape, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle
-
Field Details
-
DONEDRAWINGPROP
Fired after every completed paint pass.- See Also:
-
TITLETEXTCHANGE
Fired when the plot title text changes.- See Also:
-
TITLEFONTCHANGE
Fired when the plot title font changes.- See Also:
-
XLABELTEXTCHANGE
Fired when the x-axis label text changes.- See Also:
-
YLABELTEXTCHANGE
Fired when the y-axis label text changes.- See Also:
-
AXESFONTCHANGE
Fired when the axes font changes.- See Also:
-
STATUSFONTCHANGE
Fired when the status/feedback font changes.- See Also:
-
LOGZCHANGE
Fired when log-Z mode changes (2D histograms).- See Also:
-
COLORMAPCHANGE
Fired when the color map changes (2D histograms / heatmaps).- See Also:
-
_screenToRawWorld
Transforms screen → raw-world (null when component has no valid size). -
_rawWorldToScreen
Transforms raw-world → screen (null when component has no valid size). -
_plotData
The data backing this canvas. -
_parameters
Visual and numerical parameters (axis labels, fonts, log scale, etc.).
-
-
Constructor Details
-
PlotCanvas
Creates aPlotCanvasfor the given dataset.- Parameters:
plotData- the initial dataset (null→ empty XYXY data)plotTitle- plot title (may benull)xLabel- x-axis label (may benull)yLabel- y-axis label (may benull)
-
-
Method Details
-
removeNotify
public void removeNotify()- Overrides:
removeNotifyin classJComponent
-
standUp
public void standUp()Starts the timer and notifies listeners that the canvas is active. -
shutDown
public void shutDown()Stops the timer and notifies listeners that the canvas is shutting down. -
setPlotData
Replaces the dataset and recomputes the world system.- Parameters:
plotData- the new dataset (null→ empty XYXY data)
-
getPlotData
Returns the dataset backing this canvas.- Returns:
- the current
PlotData(nevernullafter construction)
-
clearData
public void clearData()Clears all data from every curve.- See Also:
-
getType
Returns the currentPlotDataType.- Returns:
- data type of the current dataset
-
getParameters
Returns the plot parameters object.- Returns:
- current
PlotParameters
-
getTitle
Returns the plot title.- Returns:
- title string (may be
null)
-
isBarPlot
public boolean isBarPlot()Returnstrueif this canvas is configured as a bar plot.- Returns:
trueif theRenderHint.BARPLOThint is set
-
setParent
Sets the optional parent component (usually aPlotPanel).- Parameters:
parent- parent component, ornull
-
setToolBar
Sets the toolbar that owns this canvas.- Parameters:
toolBar- the toolbar, ornullif there is no toolbar
-
showPreferencesEditor
public void showPreferencesEditor()Opens the plot preferences dialog. -
getWorld
Returns the visible region in raw-world coordinates.When log axes are active, this rectangle is in log₁₀(data) space.
- Returns:
- the world rectangle (never
nullafter construction)
-
getActiveBounds
Returns the pixel bounds of the active (data) area within the component.- Returns:
- active bounds, or
nullif the component has no size yet
-
isXLogActive
public boolean isXLogActive()Returnstrueif log-10 scaling is active on the x-axis.- Returns:
truewhen x log-scaling is both requested and valid
-
isYLogActive
public boolean isYLogActive()Returnstrueif log-10 scaling is active on the y-axis.- Returns:
truewhen y log-scaling is both requested and valid
-
getPlotTicks
Returns the tick-mark renderer for this canvas.- Returns:
- the
PlotTicks(nevernullafter construction)
-
plotPanel
Returns thePlotPanelthat contains this canvas, if any.- Returns:
- the parent
PlotPanel, ornull
-
needsRedraw
public void needsRedraw(boolean rescale) Signals that this canvas needs a repaint, optionally requesting a world rescale. Safe to call from any thread; the actual work happens on the next timer tick.- Parameters:
rescale- iftrue, the world system is recomputed before repainting
-
setWorldSystem
public void setWorldSystem()Recomputes the world system from the current data and plot parameters.Handles manual limits, algorithmic (NiceScale) limits, and log-axis bounds. Activates log scaling only when the final data range is strictly positive.
-
getDataWorld
Returns the visible region in data (linear) coordinates.- Returns:
- data-space rectangle, or
nullif the world system is uninitialised
-
paintComponent
Paints the canvas: background, data, frame, ticks, legend, extra text. FiresDONEDRAWINGPROPwhen complete.- Overrides:
paintComponentin classJComponent- Parameters:
g- graphics context
-
zoomToRect
Zooms to a rubber-band rectangle specified in screen (pixel) coordinates. Rectangles smaller than 15×15 pixels are ignored to prevent accidental micro-zooms.- Parameters:
rbrect- rubber-band rectangle in screen coordinates
-
scale
public void scale(double amount) Scales the visible area byamountaround its center. Values greater than 1 zoom out; values less than 1 zoom in.- Parameters:
amount- scale factor (> 0)
-
addPlotChangeListener
Registers aPlotChangeListenerfor lifecycle events. Duplicate registrations are silently de-duplicated.- Parameters:
listener- the listener to add (non-null)
-
removePlotChangeListener
Removes a previously registeredPlotChangeListener.- Parameters:
listener- the listener to remove (ignored ifnullor not registered)
-
remoteFirePropertyChange
Triggers a property-change event on behalf of another object (e.g. a sub-component that cannot fire its own property changes).- Parameters:
propName- property nameoldValue- old valuenewValue- new value
-
dataSetChanged
Called by the data model when curve data changes. Schedules a rescaled redraw.- Specified by:
dataSetChangedin interfaceDataChangeListener- Parameters:
plotData- the plot data that changedcurve- the specific curve that changedtype- the type of change
-
screenToRawWorld
Converts a screen (pixel) point to raw-world coordinates.Raw world is the coordinate system of
_worldSystem. When log axes are active, raw world is in log₁₀(data) space. Use this for rubber-band zoom operations.- Parameters:
screenPoint- screen point in component coordinates (non-null)rawPoint- output point filled with raw-world coordinates (non-null)- Throws:
IllegalArgumentException- if either argument isnull
-
screenToRawWorld
Converts a screen (pixel) rectangle to a raw-world rectangle.Use this for rubber-band zoom: the result can be assigned directly into
_worldSystem.- Parameters:
screenRect- screen rectangle in component coordinatesrawRect- output rectangle in raw-world coordinates (non-null)- Throws:
IllegalArgumentException- ifrawRectisnull
-
screenToData
Converts a screen (pixel) point to data coordinates (always linear units).Use this for mouse readouts and hit-tests in data space.
- Parameters:
screenPoint- screen point in component coordinatesdataPoint- output point in data coordinates (non-null)- Throws:
IllegalArgumentException- ifdataPointisnull
-
screenToData
Converts a screen rectangle to data-space bounds (always linear units).Do not use this to update
_worldSystem; for zoom you want raw-world coordinates.- Parameters:
screenRect- screen rectangle in component coordinatesdataRect- output rectangle in data coordinates (non-null)- Throws:
IllegalArgumentException- ifdataRectisnull
-
dataToScreen
Converts a data point (linear units) to screen (pixel) coordinates.Handles log-axis conversion internally (data → log₁₀ → raw-world → screen).
- Parameters:
screenPt- output screen point (non-null)dataPoint- input data point in linear units (non-null)- Returns:
trueon success;falseif the point is invalid for the current axes (e.g. non-positive on a log axis) or transforms are unavailable
-
dataToScreen
Converts a data rectangle (linear units) to a screen rectangle.- Parameters:
screenRect- output screen rectangle (non-null)dataRect- input data rectangle in linear units (non-null)- Returns:
trueon success;falseif any corner is invalid for the current axes or transforms are unavailable
-
dataToScreen
Converts a data rectangle specified by two corners to a screen rectangle.- Parameters:
dataX0- data-space x₀ (linear)dataY0- data-space y₀ (linear)dataX1- data-space x₁ (linear)dataY1- data-space y₁ (linear)- Returns:
- screen rectangle, or
nullif any corner is invalid
-
dataToScreen
Converts a single data point to a screen point.- Parameters:
dataX- data-space x (linear)dataY- data-space y (linear)- Returns:
- screen point, or
nullif the point is invalid for the current axes
-
setAffineTransforms
protected void setAffineTransforms()Rebuilds the affine transforms from the current world system and active bounds.
-