Package com.dkt.graphics.canvas
Class Canvas
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JPanel
com.dkt.graphics.canvas.Canvas
- All Implemented Interfaces:
ActionListener,ImageObserver,MenuContainer,Serializable,EventListener,Accessible
This class represents a basic canvas, it has some features that may seem
useless... they are...
Within the canvas there are 2 types of
Within the canvas there are 2 types of
GraphicE, fixed and mobile.
fixed elements are only redrawn when the canvas is resized or when
specifically told to.- Author:
- Federico Vera <[email protected]>
- See Also:
-
Nested Class Summary
Nested classes/interfaces inherited from class javax.swing.JPanel
JPanel.AccessibleJPanelNested 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
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
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidvoidAdds aGraphicEto the canvas.
This method doesn't check if the element is already contained on the canvas, this mean, that you can add elements twice (With no particular gain).voidAdds a new fixedGraphicEto the canvasbooleanTells if the canvas is repainting itself automaticallybooleanTells if the canvas is being centered.
Note: the default value isfalsebooleanTells if the canvas is centering automatically the origin of coordinates.booleanTells if aGraphicEis already being painted on the canvas.Retrieves thePaintused as background on the drawable area of the canvasRetrieves thePaintof the border of the drawable areaintgetXOff()Retrieves the horizontal offset of the drawing area in the canvas.intgetXSize()Retrieves the horizontal size of the drawable areaintgetYOff()Retrieves the vertical offset of the drawing area in the canvas.intgetYSize()Retrieves the vertical size of the drawable areabooleaninDrawingArea(int x, int y) Tells if a given point is contained in the drawing area.booleanTells if the canvas is inverting the Y axisvoidmoveOrigin(int x, int y) Moves the origin of coordinates to the given position, this method is very useful when working with mathematical functions since it gives a more natural way of drawing things.voidvoidpaintDrawableArea(Graphics2D g2d, boolean back) Paints the canvas drawable area on the given graphicsbooleanRemoves a givenGraphicEfrom the canvasvoidbooleanremoveFixed(GraphicE element) Removes a given fixedGraphicEfrom the canvaslongRetrieves the time in ms for the canvas to repaint itselfvoidThis method redraws the background and then repaints the canvasvoidsendToBottom(GraphicE element) Sends the selectedGraphicEto the bottom of the canvas, so other elements will be painted on topvoidsendToFront(GraphicE element) Sends the selectedGraphicEto the top of the canvas, so it will be painted on top of all the other elements.
Note: if a new element is added it will land on top of this one.voidsetAutoRepaint(boolean repaint) Tells the canvas to repaint itself automaticallyvoidsetBackground(Color bg) voidsetCenterBounds(boolean centerBounds) Tells the canvas to center (or not) the drawable area in the panel.voidsetCenterOrigin(boolean center) Tells the canvas to center the origin of coordinates within the drawable area.voidsetDrawableAreaPaint(Paint paint) Sets the backgroundPaintof the drawable area of the canvasvoidsetDrawableBorderPaint(Paint paint) Sets the borderPaintof the drawable area of the canvasvoidsetDrawableSize(int xSize, int ySize) Sets the canvas size.
This value doesn't affect the panel's size, just the drawable area, this means that the canvas area will be of the given size.voidsetInvertYAxis(boolean invert) Tells the canvas to invert the Y axis.
This method comes in handy when plotting functions or working with physics since it gives a more natural way of drawing.voidsetRepaintDelay(int delay) The time in ms of the repaint interval.
This will not guaranty that each is repaint is done every n ms, it will only call the repaint method every n ms.voidsetShowFPS(boolean show) This method tells the canvas to print the current FPS value on the screen (it will be painted in the upper left corner above all other elements).voidsetUseAntiAliasing(boolean useAntiAliasing) Turns anti-aliasing on or offvoidsetUseFullArea(boolean fullArea) Tells the canvas to set the drawable area size to the size of the canvas.booleanTells if the canvas is rendering using antialiasing.
Note: the default value istruebooleanTells if the drawable area will be automatically set to the canvas size.Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUIMethods 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, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, hide, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingOrigin, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintImmediately, paintImmediately, print, 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, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, updateMethods 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, 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, 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
-
Constructor Details
-
Canvas
public Canvas()
-
-
Method Details
-
setDrawableSize
public void setDrawableSize(int xSize, int ySize) Sets the canvas size.
This value doesn't affect the panel's size, just the drawable area, this means that the canvas area will be of the given size.+------+----+ | | | |canvas| | | | | +------+ | | panel | +-----------+- Parameters:
xSize- horizontal sizeySize- vertical size- Throws:
InvalidArgumentException- if either size is less than 1
-
setCenterBounds
public void setCenterBounds(boolean centerBounds) Tells the canvas to center (or not) the drawable area in the panel.+--------------+ | | | +--------+ | | | | | | | canvas | | | | | | | +--------+ | | panel | +--------------+- Parameters:
centerBounds-trueto center the bounds anfalseotherwise
-
centerBounds
public boolean centerBounds()Tells if the canvas is being centered.
Note: the default value isfalse- Returns:
trueif the canvas is being centered andfalseotherwise
-
useFullArea
public boolean useFullArea()Tells if the drawable area will be automatically set to the canvas size.
Note: the default value isfalse- Returns:
trueif the drawable area is the canvas size, andfalseotherwise.
-
setUseFullArea
public void setUseFullArea(boolean fullArea) Tells the canvas to set the drawable area size to the size of the canvas.- Parameters:
fullArea-truefor the canvas and drawable area to have the same size, andfalseto set it manually.
-
getXSize
public int getXSize()Retrieves the horizontal size of the drawable area- Returns:
- horizontal size in px
-
getYSize
public int getYSize()Retrieves the vertical size of the drawable area- Returns:
- vertical size in px
-
sendToBottom
Sends the selectedGraphicEto the bottom of the canvas, so other elements will be painted on top- Parameters:
element-GraphicEto be send to the bottom
-
sendToFront
Sends the selectedGraphicEto the top of the canvas, so it will be painted on top of all the other elements.
Note: if a new element is added it will land on top of this one.- Parameters:
element-GraphicEto be send to the front
-
add
Adds aGraphicEto the canvas.
This method doesn't check if the element is already contained on the canvas, this mean, that you can add elements twice (With no particular gain).- Parameters:
element- element that will be added- See Also:
-
contains
Tells if aGraphicEis already being painted on the canvas.- Parameters:
element- element to test- Returns:
trueif the element is contained andfalseotherwise
-
remove
Removes a givenGraphicEfrom the canvas- Parameters:
element- element to remove- Returns:
trueif the element was contained andfalseotherwise
-
removeAll
public void removeAll() -
addFixed
Adds a new fixedGraphicEto the canvas- Parameters:
element- element that you want to add
-
removeFixed
Removes a given fixedGraphicEfrom the canvas- Parameters:
element- element to remove- Returns:
trueif the element was contained andfalseotherwise
-
setBackground
- Overrides:
setBackgroundin classJComponent
-
getDrawableAreaPaint
Retrieves thePaintused as background on the drawable area of the canvas- Returns:
- drawable area background paint
-
setDrawableAreaPaint
Sets the backgroundPaintof the drawable area of the canvas- Parameters:
paint- new paint- Throws:
IllegalArgumentException- if the color isnull
-
getDrawableBorderPaint
Retrieves thePaintof the border of the drawable area- Returns:
- drawable area border paint
-
setDrawableBorderPaint
Sets the borderPaintof the drawable area of the canvas- Parameters:
paint- new paint- Throws:
IllegalArgumentException- if the paint isnull
-
setInvertYAxis
public void setInvertYAxis(boolean invert) Tells the canvas to invert the Y axis.
This method comes in handy when plotting functions or working with physics since it gives a more natural way of drawing. But should be ignored most of the time, since it might break other transforms.
WARNING: this method does its magic using anAffineTransform, so this basically means that it draws in the conventional way and then invert the image, so text and images will appear inverted.- Parameters:
invert-trueif you wish to invert the Y axis andfalseotherwise
-
invertYAxis
public boolean invertYAxis()Tells if the canvas is inverting the Y axis- Returns:
trueif the canvas is inverting the Y axis andfalseotherwise
-
moveOrigin
public void moveOrigin(int x, int y) Moves the origin of coordinates to the given position, this method is very useful when working with mathematical functions since it gives a more natural way of drawing things.- Parameters:
x- new X coordinate of the originy- new Y coordinate of the origin
-
repaintWBackground
public void repaintWBackground()This method redraws the background and then repaints the canvas -
setCenterOrigin
public void setCenterOrigin(boolean center) Tells the canvas to center the origin of coordinates within the drawable area.- Parameters:
center-trueif you want to center the origin andfalseotherwise
-
useAntiAliasing
public boolean useAntiAliasing()Tells if the canvas is rendering using antialiasing.
Note: the default value istrue- Returns:
trueif antialiasing is on andfalseotherwise
-
setUseAntiAliasing
public void setUseAntiAliasing(boolean useAntiAliasing) Turns anti-aliasing on or off- Parameters:
useAntiAliasing-trueto turn antialiasing on, andfalseto turn it off.
-
setAutoRepaint
public void setAutoRepaint(boolean repaint) Tells the canvas to repaint itself automatically- Parameters:
repaint-trueif the canvas should repaint itself andfalseotherwise- See Also:
-
autoRepaint
public boolean autoRepaint()Tells if the canvas is repainting itself automatically- Returns:
- repaint
trueif the canvas is repainting itself andfalseotherwise - See Also:
-
setRepaintDelay
public void setRepaintDelay(int delay) The time in ms of the repaint interval.
This will not guaranty that each is repaint is done every n ms, it will only call the repaint method every n ms.- Parameters:
delay- time in ms- Throws:
InvalidArgumentException- if the delay is less than 1- See Also:
-
repaintDelay
public long repaintDelay()Retrieves the time in ms for the canvas to repaint itself- Returns:
- time in ms
- See Also:
-
centerOrigin
public boolean centerOrigin()Tells if the canvas is centering automatically the origin of coordinates.not centered centered +------------+ +------------+ |*(0,0) | | | | | | | | | | *(0,0) | | | | | | canvas | | canvas | +------------+ +------------+- Returns:
trueif the origin is centered andfalseotherwise
-
setShowFPS
public void setShowFPS(boolean show) This method tells the canvas to print the current FPS value on the screen (it will be painted in the upper left corner above all other elements).
Note: ifshowFPSis set totrueit will most likely have a small impact on performance (usually we draw hundreds of thousands ofGraphicE, but in small applications with very high FPS the impact is quite noticeable).- Parameters:
show-trueif you want to show the FPS andfalseotherwise
-
paintDrawableArea
Paints the canvas drawable area on the given graphics- Parameters:
g2d- Where to paintback-trueif you want to paint the background andfalseotherwise (falseis needed when painting with transparent components.- Throws:
IllegalArgumentException- if the g2d isnull
-
paintComponent
- Overrides:
paintComponentin classJComponent
-
actionPerformed
- Specified by:
actionPerformedin interfaceActionListener
-
inDrawingArea
public boolean inDrawingArea(int x, int y) Tells if a given point is contained in the drawing area.- Parameters:
x- X coordinate of the pointy- Y coordinate of the point- Returns:
trueif the point is contained in the drawing area, andfalseotherwise
-
getXOff
public int getXOff()Retrieves the horizontal offset of the drawing area in the canvas.- Returns:
- horizontal offset in px
-
getYOff
public int getYOff()Retrieves the vertical offset of the drawing area in the canvas.- Returns:
- vertical offset in px
-