Class Canvas

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

    public final class Canvas
    extends javax.swing.JPanel
    implements java.awt.event.ActionListener
    This class represents a basic canvas, it has some features that may seem useless... they are...

    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.
    See Also:
    Serialized Form
    • Nested Class Summary

      • 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
      • Nested classes/interfaces inherited from class java.awt.Container

        java.awt.Container.AccessibleAWTContainer
      • Nested classes/interfaces inherited from class javax.swing.JComponent

        javax.swing.JComponent.AccessibleJComponent
      • Nested classes/interfaces inherited from class javax.swing.JPanel

        javax.swing.JPanel.AccessibleJPanel
    • Field Summary

      • Fields inherited from class java.awt.Component

        accessibleContext, 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
      • 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_WINDOW
    • Constructor Summary

      Constructors 
      Constructor Description
      Canvas()
      Creates a new instance
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void actionPerformed​(java.awt.event.ActionEvent ae)  
      void add​(GraphicE element)
      Adds a GraphicE to 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).
      void addFixed​(GraphicE element)
      Adds a new fixed GraphicE to the canvas
      boolean autoRepaint()
      Tells if the canvas is repainting itself automatically
      boolean centerBounds()
      Tells if the canvas is being centered.
      Note: the default value is false
      boolean centerOrigin()
      Tells if the canvas is centering automatically the origin of coordinates.
      boolean contains​(GraphicE element)
      Tells if a GraphicE is already being painted on the canvas.
      java.awt.Paint getDrawableAreaPaint()
      Retrieves the Paint used as background on the drawable area of the canvas
      java.awt.Paint getDrawableBorderPaint()
      Retrieves the Paint of the border of the drawable area
      int getXOff()
      Retrieves the horizontal offset of the drawing area in the canvas.
      int getXSize()
      Retrieves the horizontal size of the drawable area
      int getYOff()
      Retrieves the vertical offset of the drawing area in the canvas.
      int getYSize()
      Retrieves the vertical size of the drawable area
      boolean inDrawingArea​(int x, int y)
      Tells if a given point is contained in the drawing area.
      boolean invertYAxis()
      Tells if the canvas is inverting the Y axis
      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.
      void paintComponent​(java.awt.Graphics g)  
      void paintDrawableArea​(java.awt.Graphics2D g2d, boolean back)
      Paints the canvas drawable area on the given graphics
      boolean remove​(GraphicE element)
      Removes a given GraphicE from the canvas
      void removeAll()  
      boolean removeFixed​(GraphicE element)
      Removes a given fixed GraphicE from the canvas
      long repaintDelay()
      Retrieves the time in ms for the canvas to repaint itself
      void repaintWBackground()
      This method redraws the background and then repaints the canvas
      void sendToBottom​(GraphicE element)
      Sends the selected GraphicE to the bottom of the canvas, so other elements will be painted on top
      void sendToFront​(GraphicE element)
      Sends the selected GraphicE to 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.
      void setAutoRepaint​(boolean repaint)
      Tells the canvas to repaint itself automatically
      void setBackground​(java.awt.Color bg)  
      void setCenterBounds​(boolean centerBounds)
      Tells the canvas to center (or not) the drawable area in the panel.
      void setCenterOrigin​(boolean center)
      Tells the canvas to center the origin of coordinates within the drawable area.
      void setDrawableAreaPaint​(java.awt.Paint paint)
      Sets the background Paint of the drawable area of the canvas
      void setDrawableBorderPaint​(java.awt.Paint paint)
      Sets the border Paint of the drawable area of the canvas
      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.
      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.
      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.
      void setShowFPS​(boolean show)
      This method tells the canvas to print the current FPS value on the screen (it will be painted on the upper left corner above all other elements).
      void setUseAntiAliasing​(boolean useAntiAliasing)
      Turns anti-aliasing on or off
      void setUseFullArea​(boolean fullArea)
      Tells the canvas to set the drawable area size to the size of the canvas.
      boolean useAntiAliasing()
      Tells if the canvas is rendering using anti-aliasing.
      Note: the default value is true
      boolean useFullArea()
      Tells if the drawable area will be automatically set to the canvas size.
      • 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, 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
      • 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, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusDownCycle, validate, validateTree
      • 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, 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, update
      • Methods inherited from class javax.swing.JPanel

        getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
    • Constructor Detail

      • Canvas

        public Canvas()
        Creates a new instance
    • Method Detail

      • 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 size
        ySize - 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 - true to center the bounds an false otherwise
      • centerBounds

        public boolean centerBounds()
        Tells if the canvas is being centered.
        Note: the default value is false
        Returns:
        true if the canvas is being centered and false otherwise
      • useFullArea

        public boolean useFullArea()
        Tells if the drawable area will be automatically set to the canvas size.
        Note: the default value is false
        Returns:
        true if the drawable area is the canvas size, and false otherwise.
      • setUseFullArea

        public void setUseFullArea​(boolean fullArea)
        Tells the canvas to set the drawable area size to the size of the canvas.
        Parameters:
        fullArea - true for the canvas and drawable area to have the same size, and false to 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

        public void sendToBottom​(GraphicE element)
        Sends the selected GraphicE to the bottom of the canvas, so other elements will be painted on top
        Parameters:
        element - GraphicE to be send to the bottom
      • sendToFront

        public void sendToFront​(GraphicE element)
        Sends the selected GraphicE to 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 - GraphicE to be send to the front
      • contains

        public boolean contains​(GraphicE element)
        Tells if a GraphicE is already being painted on the canvas.
        Parameters:
        element - element to test
        Returns:
        true if the element is contained and false otherwise
      • remove

        public boolean remove​(GraphicE element)
        Removes a given GraphicE from the canvas
        Parameters:
        element - element to remove
        Returns:
        true if the element was contained and false otherwise
      • removeAll

        public void removeAll()
        Overrides:
        removeAll in class java.awt.Container
      • addFixed

        public void addFixed​(GraphicE element)
        Adds a new fixed GraphicE to the canvas
        Parameters:
        element - element that you want to add
      • removeFixed

        public boolean removeFixed​(GraphicE element)
        Removes a given fixed GraphicE from the canvas
        Parameters:
        element - element to remove
        Returns:
        true if the element was contained and false otherwise
      • setBackground

        public void setBackground​(java.awt.Color bg)
        Overrides:
        setBackground in class javax.swing.JComponent
      • getDrawableAreaPaint

        public java.awt.Paint getDrawableAreaPaint()
        Retrieves the Paint used as background on the drawable area of the canvas
        Returns:
        drawable area background paint
      • setDrawableAreaPaint

        public void setDrawableAreaPaint​(java.awt.Paint paint)
        Sets the background Paint of the drawable area of the canvas
        Parameters:
        paint - new paint
        Throws:
        java.lang.IllegalArgumentException - if the color is null
      • getDrawableBorderPaint

        public java.awt.Paint getDrawableBorderPaint()
        Retrieves the Paint of the border of the drawable area
        Returns:
        drawable area border paint
      • setDrawableBorderPaint

        public void setDrawableBorderPaint​(java.awt.Paint paint)
        Sets the border Paint of the drawable area of the canvas
        Parameters:
        paint - new paint
        Throws:
        java.lang.IllegalArgumentException - if the paint is null
      • 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 it's magic using an AffineTransform, 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 - true if you wish to invert the Y axis and false otherwise
      • invertYAxis

        public boolean invertYAxis()
        Tells if the canvas is inverting the Y axis
        Returns:
        true if the canvas is inverting the Y axis and false otherwise
      • 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 origin
        y - 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 - true if you want to center the origin and false otherwise
      • useAntiAliasing

        public boolean useAntiAliasing()
        Tells if the canvas is rendering using anti-aliasing.
        Note: the default value is true
        Returns:
        true if anti-alising is on and false otherwise
      • setUseAntiAliasing

        public void setUseAntiAliasing​(boolean useAntiAliasing)
        Turns anti-aliasing on or off
        Parameters:
        useAntiAliasing - true to turn anti-aliasing on, and false to turn it off.
      • setAutoRepaint

        public void setAutoRepaint​(boolean repaint)
        Tells the canvas to repaint itself automatically
        Parameters:
        repaint - true if the canvas should repaint itself and false otherwise
        See Also:
        setRepaintDelay(int)
      • autoRepaint

        public boolean autoRepaint()
        Tells if the canvas is repainting itself automatically
        Returns:
        repaint true if the canvas is repainting itself and false otherwise
        See Also:
        setRepaintDelay(int)
      • 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:
        setAutoRepaint(boolean)
      • repaintDelay

        public long repaintDelay()
        Retrieves the time in ms for the canvas to repaint itself
        Returns:
        time in ms
        See Also:
        setAutoRepaint(boolean)
      • 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:
        true if the origin is centered and false otherwise
      • setShowFPS

        public void setShowFPS​(boolean show)
        This method tells the canvas to print the current FPS value on the screen (it will be painted on the upper left corner above all other elements).
        Note: if showFPS is set to true it will most likely have a small impact on performance (usually we draw hundreds of thousands of GraphicE, but in small applications with very high FPS the impact is quite noticeable).
        Parameters:
        show - true if you want to show the FPS and false otherwise
      • paintDrawableArea

        public void paintDrawableArea​(java.awt.Graphics2D g2d,
                                      boolean back)
        Paints the canvas drawable area on the given graphics
        Parameters:
        g2d - Where to paint
        back - true if you want to paint the background and false otherwise (false is needed when painting with transparent components.
        Throws:
        java.lang.IllegalArgumentException - if the g2d is null
      • paintComponent

        public void paintComponent​(java.awt.Graphics g)
        Overrides:
        paintComponent in class javax.swing.JComponent
      • actionPerformed

        public void actionPerformed​(java.awt.event.ActionEvent ae)
        Specified by:
        actionPerformed in interface java.awt.event.ActionListener
      • 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 point
        y - Y coordinate of the point
        Returns:
        true if the point is contained in the drawing area, and false otherwise
      • 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