Class DrawingPanel

java.lang.Object
DrawingPanel
All Implemented Interfaces:
ImageObserver

public final class DrawingPanel extends Object implements ImageObserver
DrawingPanel is a simplified Java drawing window class to accompany Building Java Programs textbook and associated materials.

Authors: Stuart Reges (University of Washington) and Marty Stepp.

Version: 4.06, 2022/04/07 (to accompany BJP 5th edition).

You can always download the latest DrawingPanel from http://www.buildingjavaprograms.com/drawingpanel/DrawingPanel.java .

For more information and related materials, please visit www.buildingjavaprograms.com .

COMPATIBILITY NOTE: This version of DrawingPanel requires Java 8 or higher. To make this file work on Java 7 and lower, you must make two small modifications to its source code. Search for the two occurrences of the annotation @FunctionalInterface and comment them out or remove those lines. Then the file should compile and run properly on older versions of Java.

Description:

The DrawingPanel class provides a simple interface for drawing persistent images using a Graphics object. An internal BufferedImage object is used to keep track of what has been drawn. A client of the class simply constructs a DrawingPanel of a particular size and then draws on it with the Graphics object, setting the background color if they so choose.

The intention is that this custom library will mostly "stay out of the way" so that the client mostly interacts with a standard Java java.awt.Graphics object, and therefore most of the experience gained while using this library will transfer to Java graphics programming in other contexts. DrawingPanel is not intended to be a full rich graphical library for things like object-oriented drawing of shapes, animations, creating games, etc.

Example basic usage:

Here is a canonical example of creating a DrawingPanel of a given size and using it to draw a few shapes.

 // basic usage example
 DrawingPanel panel = new DrawingPanel(600, 400);
 Graphics g = panel.getGraphics();
 g.setColor(Color.RED);
 g.fillRect(17, 45, 139, 241);
 g.drawOval(234, 77, 100, 100);
 ...
 

To ensure that the image is always displayed, a timer calls repaint at regular intervals.

Pixel processing (new in BJP 4th edition):

This version of DrawingPanel allows you to loop over the pixels of an image. You can process each pixel as a Color object (easier OO interface, but takes more CPU and memory to run) or as a 32-bit RGB integer (clunkier to use, but much more efficient in runtime and memory usage). Look at the methods get/setPixel(s) to get a better idea.

 // example of horizontally flipping an image
 public static void flipHorizontal(DrawingPanel panel) {
     int width  = panel.getWidth();
     int height = panel.getHeight();
     int[][] pixels = panel.getPixelsRGB();
     for (int row = 0; row < height; row++) {
         for (int col = 0; col < width / 2; col++) {
             // swap this pixel with the one opposite it
             int col2 = width - 1 - col;
             int temp = pixels[row][col];
             pixels[row][col] = pixels[row][col2];
             pixels[row][col2] = temp;
         }
     }
     panel.setPixels(pixels);
 }
 

Event listeners and lambdas (new in BJP 4th edition):

With Java 8, you can now attach event handlers to listen to keyboard and mouse events that occur in a DrawingPanel using a lambda function. For example:

 // example of attaching a mouse click handler using Java 8
 panel.onClick( (x, y) -> System.out.println(x + " " + y) );
 

Debugging facilities (new in BJP 4th edition):

This version now includes an inner class named DebuggingGraphics that keeps track of how many times various drawing methods are called. It includes a showCounts method for the DrawingPanel itself that allows a client to examine this. The panel will record basic drawing methods performed by a version of the Graphics class obtained by calling getDebuggingGraphics :

 // example of debugging counts of graphics method calls
 Graphics g = panel.getDebuggingGraphics();
 

Novices will be encouraged to simply print it at the end of main, as in:

 System.out.println(panel.getCounts());
 

History and recent changes:

2022/04/07 - Minor update to remove a security manager-related compiler warning in JDK 17+. 2016/07/25 - Added and cleaned up BJP4 features, static anti-alias settings, bug fixes.

2016/03/07 - Code cleanup and improvements to JavaDoc comments for BJP4 release.

2015/09/04 - Now includes methods for get/setting individual pixels and all pixels on the drawing panel. This helps facilitate 2D array-based pixel-processing exercises and problems for Building Java Programs, 4th edition. - Code cleanup and reorganization. Now better alphabetization/formatting of members and encapsulation. Commenting also augmented throughout code.

2015/04/09 - Now includes a DebuggingGraphics inner class that keeps track of how many times various drawing methods are called. All additions are commented (search for "DebuggingGraphics")

2011/10/25 - save zoomed images (2011/10/25)

2011/10/21 - window no longer moves when zoom changes - grid lines

  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static interface 
    This functional interface is provided to allow Java 8 clients to write lambda functions to handle key events that occur in a DrawingPanel.
    static interface 
    This functional interface is provided to allow Java 8 clients to write lambda functions to handle mouse events that occur in a DrawingPanel.
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final String
    An internal constant for setting system properties; clients should not use this.
    static final String
    An internal constant for setting system properties; clients should not use this.
    static final String
    An internal constant for setting system properties; clients should not use this.
    static final String
    An internal constant for setting system properties; clients should not use this.
    static final int
    The default height of a DrawingPanel in pixels, if none is supplied at construction (400 pixels).
    static final int
    The default width of a DrawingPanel in pixels, if none is supplied at construction (500 pixels).
    static final String
    An internal constant for setting system properties; clients should not use this.
    static final String
    An internal constant for setting system properties; clients should not use this.
    static final String
    An internal constant for setting system properties; clients should not use this.
    static final int
    An RGB integer representing alpha at 100% opacity (0xff000000).
    static final int
    An RGB integer representing 100% blue (0x000000ff).
    static final int
    An RGB integer representing 100% green (0x0000ff00).
    static final int
    An RGB integer representing 100% red (0x00ff0000).
    static final String
    An internal constant for setting system properties; clients should not use this.

    Fields inherited from interface java.awt.image.ImageObserver

    ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
  • Constructor Summary

    Constructors
    Constructor
    Description
    Constructs a drawing panel with a default width and height enclosed in a window.
    DrawingPanel(int width, int height)
    Constructs a drawing panel of given width and height enclosed in a window.
    DrawingPanel(File imageFile)
    Constructs a drawing panel that displays the image from the given file enclosed in a window.
    DrawingPanel(String imageFileName)
    Constructs a drawing panel that displays the image from the given file name enclosed in a window.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    Adds the given event listener to respond to key events on this panel.
    void
    Adds the given event listener to respond to mouse events on this panel.
    void
    Erases all drawn shapes/lines/colors from the panel.
    static int
    getAlpha(int rgb)
    Returns the alpha (opacity) component of the given RGB pixel from 0-255.
    static int
    getBlue(int rgb)
    Returns the blue component of the given RGB pixel from 0-255.
    Returns a map of counts of occurrences of calls of various drawing methods.
    A variation of getGraphics that returns an object that records a count for various drawing methods.
    Obtain the Graphics object to draw on the panel.
    static int
    getGreen(int rgb)
    Returns the green component of the given RGB pixel from 0-255.
    int
    Returns the drawing panel's height in pixels.
    getPixel(int x, int y)
    Returns the color of the pixel at the given x/y coordinate as a Color object.
    int
    getPixelRGB(int x, int y)
    Returns the color of the pixel at the given x/y coordinate as an RGB integer.
    Color[][]
    Returns the colors of all pixels in this DrawingPanel as a 2-D array of Color objects.
    int[][]
    Returns the colors of all pixels in this DrawingPanel as a 2-D array of RGB integers.
    static int
    getRed(int rgb)
    Returns the red component of the given RGB pixel from 0-255.
    static String
    Returns the file name used for saving all DrawingPanel instances.
    Returns the drawing panel's pixel size (width, height) as a Dimension object.
    int
    Returns the drawing panel's width in pixels.
    int
    Returns the drawing panel's x-coordinate on the screen.
    int
    Returns the drawing panel's y-coordinate on the screen.
    int
    Returns the drawing panel's current zoom factor.
    boolean
    imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
    Internal method; notifies the panel when images are loaded and updated.
    static boolean
    Returns true if DrawingPanel instances should anti-alias (smooth) their graphics.
    static boolean
    Returns true if the class is in "headless" mode, meaning that it is running on a server without a graphical user interface.
    Loads an image from the given file on disk and returns it as an Image object.
    loadImage(String filename)
    Loads an image from the given file on disk and returns it as an Image object.
    static boolean
    Internal method; returns whether the 'main' thread is still running.
    void
    Adds an event handler for mouse clicks.
    void
    Adds an event handler for mouse drags.
    void
    Adds an event handler for mouse enters.
    void
    Adds an event handler for mouse exits.
    void
    Adds an event handler for key presses.
    void
    Adds an event handler for key releases.
    void
    Adds an event handler for mouse clicks.
    void
    Adds an event handler for mouse button down events.
    void
    Adds an event handler for mouse drags.
    void
    Adds an event handler for mouse enters.
    void
    Adds an event handler for mouse exits.
    void
    Adds an event handler for mouse movement.
    void
    Adds an event handler for mouse button up events.
    void
    Adds an event handler for mouse movement.
    void
    save(File file)
    Takes the current contents of the drawing panel and writes them to the given file.
    void
    save(String filename)
    Takes the current contents of the drawing panel and writes them to the given file.
    static void
    Saves every DrawingPanel instance that is active.
    void
    Takes the current contents of the drawing panel and writes them to the given file.
    void
    saveAnimated(String filename)
    Takes the current contents of the drawing panel and writes them to the given file.
    void
    setAlwaysOnTop(boolean alwaysOnTop)
    Sets whether the panel will always cover other windows (default false).
    void
    setAntiAlias(boolean antiAlias)
    Sets whether the panel should use anti-aliased / smoothed graphics (default true).
    static void
    Sets whether DrawingPanel instances should anti-alias (smooth) their pixels by default.
    void
    setBackground(int rgb)
    Sets the background color of the drawing panel to be the color represented by the given RGB integer.
    void
    Sets the background color of the drawing panel to be the given color.
    void
    setGridLines(boolean gridLines)
    Enables or disables the drawing of grid lines on top of the image to help with debugging sizes and coordinates.
    void
    setGridLines(boolean gridLines, int pxGap)
    Enables or disables the drawing of grid lines on top of the image to help with debugging sizes and coordinates.
    static void
    Sets the class to run in "headless" mode, with no graphical output on screen.
    void
    setHeight(int height)
    Sets the drawing panel's height in pixels to the given value.
    void
    setPixel(int x, int y, int rgb)
    Sets the color of the pixel at the given x/y coordinate to be the color represented by the given RGB integer.
    void
    setPixel(int x, int y, Color color)
    Sets the color of the pixel at the given x/y coordinate to be the given color.
    void
    setPixelRGB(int x, int y, int rgb)
    Sets the color of the pixel at the given x/y coordinate to be the color represented by the given RGB integer.
    void
    setPixels(int[][] pixels)
    Sets the colors of all pixels in this DrawingPanel to the colors represented by the given 2-D array of RGB integers.
    void
    setPixels(Color[][] pixels)
    Sets the colors of all pixels in this DrawingPanel to the colors in the given 2-D array of Color objects.
    void
    setPixelsRGB(int[][] pixels)
    Sets the colors of all pixels in this DrawingPanel to the colors represented by the given 2-D array of RGB integers.
    static void
    Sets the file to be used when saving graphical output for all DrawingPanels.
    static void
    Sets the filename to be used when saving graphical output for all DrawingPanels.
    void
    setSize(int width, int height)
    Sets the drawing panel's pixel size (width, height) to the given values.
    void
    setVisible(boolean visible)
    Show or hide the drawing panel on the screen.
    void
    setWidth(int width)
    Sets the drawing panel's width in pixels to the given value.
    void
    sleep(int millis)
    Causes the program to pause for the given amount of time in milliseconds.
    void
    Moves the drawing panel window on top of other windows so it can be seen.
    static int
    toRgbInteger(int r, int g, int b)
    Returns an RGB integer made from the given red, green, and blue components from 0-255.
    static int
    toRgbInteger(int alpha, int r, int g, int b)
    Returns an RGB integer made from the given alpha, red, green, and blue components from 0-255.
    void
    zoom(int zoomFactor)
    Zooms the drawing panel in/out to the given factor.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

    • PIXEL_ALPHA

      public static final int PIXEL_ALPHA
      An RGB integer representing alpha at 100% opacity (0xff000000).
      See Also:
    • PIXEL_BLUE

      public static final int PIXEL_BLUE
      An RGB integer representing 100% blue (0x000000ff).
      See Also:
    • PIXEL_GREEN

      public static final int PIXEL_GREEN
      An RGB integer representing 100% green (0x0000ff00).
      See Also:
    • PIXEL_RED

      public static final int PIXEL_RED
      An RGB integer representing 100% red (0x00ff0000).
      See Also:
    • DEFAULT_WIDTH

      public static final int DEFAULT_WIDTH
      The default width of a DrawingPanel in pixels, if none is supplied at construction (500 pixels).
      See Also:
    • DEFAULT_HEIGHT

      public static final int DEFAULT_HEIGHT
      The default height of a DrawingPanel in pixels, if none is supplied at construction (400 pixels).
      See Also:
    • ANIMATED_PROPERTY

      public static final String ANIMATED_PROPERTY
      An internal constant for setting system properties; clients should not use this.
      See Also:
    • ANIMATION_FILE_NAME

      public static final String ANIMATION_FILE_NAME
      An internal constant for setting system properties; clients should not use this.
      See Also:
    • ANTIALIAS_PROPERTY

      public static final String ANTIALIAS_PROPERTY
      An internal constant for setting system properties; clients should not use this.
      See Also:
    • AUTO_ENABLE_ANIMATION_ON_SLEEP_PROPERTY

      public static final String AUTO_ENABLE_ANIMATION_ON_SLEEP_PROPERTY
      An internal constant for setting system properties; clients should not use this.
      See Also:
    • DIFF_PROPERTY

      public static final String DIFF_PROPERTY
      An internal constant for setting system properties; clients should not use this.
      See Also:
    • HEADLESS_PROPERTY

      public static final String HEADLESS_PROPERTY
      An internal constant for setting system properties; clients should not use this.
      See Also:
    • MULTIPLE_PROPERTY

      public static final String MULTIPLE_PROPERTY
      An internal constant for setting system properties; clients should not use this.
      See Also:
    • SAVE_PROPERTY

      public static final String SAVE_PROPERTY
      An internal constant for setting system properties; clients should not use this.
      See Also:
  • Constructor Details

    • DrawingPanel

      public DrawingPanel()
      Constructs a drawing panel with a default width and height enclosed in a window. Uses DEFAULT_WIDTH and DEFAULT_HEIGHT for the panel's size.
    • DrawingPanel

      public DrawingPanel(int width, int height)
      Constructs a drawing panel of given width and height enclosed in a window.
      Parameters:
      width - panel's width in pixels
      height - panel's height in pixels
    • DrawingPanel

      public DrawingPanel(File imageFile)
      Constructs a drawing panel that displays the image from the given file enclosed in a window. The panel will be sized exactly to fit the image inside it.
      Parameters:
      imageFile - the image file to load
      Throws:
      RuntimeException - if the image file is not found
    • DrawingPanel

      public DrawingPanel(String imageFileName)
      Constructs a drawing panel that displays the image from the given file name enclosed in a window. The panel will be sized exactly to fit the image inside it.
      Parameters:
      imageFileName - the file name/path of the image file to load
      Throws:
      RuntimeException - if the image file is not found
  • Method Details

    • getAlpha

      public static int getAlpha(int rgb)
      Returns the alpha (opacity) component of the given RGB pixel from 0-255. Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
      Parameters:
      rgb - RGB integer with alpha in bits 0-7, red in bits 8-15, green in bits 16-23, and blue in bits 24-31
      Returns:
      alpha component from 0-255
    • getBlue

      public static int getBlue(int rgb)
      Returns the blue component of the given RGB pixel from 0-255. Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
      Parameters:
      rgb - RGB integer with alpha in bits 0-7, red in bits 8-15, green in bits 16-23, and blue in bits 24-31
      Returns:
      blue component from 0-255
    • getGreen

      public static int getGreen(int rgb)
      Returns the green component of the given RGB pixel from 0-255. Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
      Parameters:
      rgb - RGB integer with alpha in bits 0-7, red in bits 8-15, green in bits 16-23, and blue in bits 24-31
      Returns:
      green component from 0-255
    • getRed

      public static int getRed(int rgb)
      Returns the red component of the given RGB pixel from 0-255. Often used in conjunction with the methods getPixelRGB, setPixelRGB, etc.
      Parameters:
      rgb - RGB integer with alpha in bits 0-7, red in bits 8-15, green in bits 16-23, and blue in bits 24-31
      Returns:
      red component from 0-255
    • getSaveFileName

      public static String getSaveFileName()
      Returns the file name used for saving all DrawingPanel instances. By default this is null, but it can be set using setSaveFileName or by setting the SAVE_PROPERTY env variable.
      Returns:
      the shared save file name
    • isAntiAliasDefault

      public static boolean isAntiAliasDefault()
      Returns true if DrawingPanel instances should anti-alias (smooth) their graphics. By default this is true, but it can be set to false using the ANTIALIAS_PROPERTY.
      Returns:
      true if anti-aliasing is enabled (default true)
    • isHeadless

      public static boolean isHeadless()
      Returns true if the class is in "headless" mode, meaning that it is running on a server without a graphical user interface.
      Returns:
      true if we are in headless mode (default false)
    • mainIsActive

      public static boolean mainIsActive()
      Internal method; returns whether the 'main' thread is still running. Used to determine whether to exit the program when the drawing panel is closed by the user. This is an internal method not meant to be called by clients.
      Returns:
      true if main thread is still running
    • saveAll

      public static void saveAll() throws IOException
      Saves every DrawingPanel instance that is active.
      Throws:
      IOException - if unable to save any of the files.
    • setAntiAliasDefault

      public static void setAntiAliasDefault(Boolean value)
      Sets whether DrawingPanel instances should anti-alias (smooth) their pixels by default. Default true. You can set this on a given DrawingPanel instance with setAntialias(boolean).
      Parameters:
      value - whether to enable anti-aliasing (default true)
    • setHeadless

      public static void setHeadless(Boolean value)
      Sets the class to run in "headless" mode, with no graphical output on screen.
      Parameters:
      value - whether to enable headless mode (default false)
    • setSaveFile

      public static void setSaveFile(File file)
      Sets the file to be used when saving graphical output for all DrawingPanels.
      Parameters:
      file - the file to use as default save file
    • setSaveFileName

      public static void setSaveFileName(String filename)
      Sets the filename to be used when saving graphical output for all DrawingPanels.
      Parameters:
      filename - the name/path of the file to use as default save file
    • toRgbInteger

      public static int toRgbInteger(int r, int g, int b)
      Returns an RGB integer made from the given red, green, and blue components from 0-255. The returned integer is suitable for use with various RGB integer methods in this class such as setPixel.
      Parameters:
      r - red component from 0-255 (bits 8-15)
      g - green component from 0-255 (bits 16-23)
      b - blue component from 0-255 (bits 24-31)
      Returns:
      RGB integer with full 255 for alpha and r-g-b in bits 8-31
      Throws:
      IllegalArgumentException - if r, g, or b is not in 0-255 range
    • toRgbInteger

      public static int toRgbInteger(int alpha, int r, int g, int b)
      Returns an RGB integer made from the given alpha, red, green, and blue components from 0-255. The returned integer is suitable for use with various RGB integer methods in this class such as setPixel.
      Parameters:
      alpha - alpha (transparency) component from 0-255 (bits 0-7)
      r - red component from 0-255 (bits 8-15)
      g - green component from 0-255 (bits 16-23)
      b - blue component from 0-255 (bits 24-31)
      Returns:
      RGB integer with the given four components
      Throws:
      IllegalArgumentException - if alpha, r, g, or b is not in 0-255 range
    • addKeyListener

      public void addKeyListener(KeyListener listener)
      Adds the given event listener to respond to key events on this panel.
      Parameters:
      listener - the key event listener to attach
    • addMouseListener

      public void addMouseListener(MouseListener listener)
      Adds the given event listener to respond to mouse events on this panel.
      Parameters:
      listener - the mouse event listener to attach
    • clear

      public void clear()
      Erases all drawn shapes/lines/colors from the panel.
    • getCounts

      public Map<String,Integer> getCounts()
      Returns a map of counts of occurrences of calls of various drawing methods. You can print this map to see how many times your graphics methods have been called to aid in debugging.
      Returns:
      map of {method name, count} pairs
    • getDebuggingGraphics

      public Graphics getDebuggingGraphics()
      A variation of getGraphics that returns an object that records a count for various drawing methods. See also: getCounts
      Returns:
      debug Graphics object
    • getGraphics

      public Graphics2D getGraphics()
      Obtain the Graphics object to draw on the panel.
      Returns:
      panel's Graphics object
    • getHeight

      public int getHeight()
      Returns the drawing panel's height in pixels.
      Returns:
      drawing panel's height in pixels
    • getPixel

      public Color getPixel(int x, int y)
      Returns the color of the pixel at the given x/y coordinate as a Color object. If nothing has been explicitly drawn on this particular pixel, the panel's background color is returned.
      Parameters:
      x - x-coordinate of pixel to retrieve
      y - y-coordinate of pixel to retrieve
      Returns:
      pixel (x, y) color as a Color object
      Throws:
      IllegalArgumentException - if (x, y) is out of range
    • getPixelRGB

      public int getPixelRGB(int x, int y)
      Returns the color of the pixel at the given x/y coordinate as an RGB integer. The individual red, green, and blue components of the RGB integer can be extracted from this by calling DrawingPanel.getRed, getGreen, and getBlue. If nothing has been explicitly drawn on this particular pixel, the panel's background color is returned. See also: getPixel.
      Parameters:
      x - x-coordinate of pixel to retrieve
      y - y-coordinate of pixel to retrieve
      Returns:
      pixel (x, y) color as an RGB integer
      Throws:
      IllegalArgumentException - if (x, y) is out of range
    • getPixels

      public Color[][] getPixels()
      Returns the colors of all pixels in this DrawingPanel as a 2-D array of Color objects. The first index of the array is the y-coordinate, and the second index is the x-coordinate. So, for example, index [r][c] represents the RGB pixel data for the pixel at position (x=c, y=r).
      Returns:
      2D array of colors (row-major)
    • getPixelsRGB

      public int[][] getPixelsRGB()
      Returns the colors of all pixels in this DrawingPanel as a 2-D array of RGB integers. The first index of the array is the y-coordinate, and the second index is the x-coordinate. So, for example, index [r][c] represents the RGB pixel data for the pixel at position (x=c, y=r). The individual red, green, and blue components of each RGB integer can be extracted from this by calling DrawingPanel.getRed, getGreen, and getBlue.
      Returns:
      2D array of RGB integers (row-major)
    • getSize

      public Dimension getSize()
      Returns the drawing panel's pixel size (width, height) as a Dimension object.
      Returns:
      panel's size
    • getWidth

      public int getWidth()
      Returns the drawing panel's width in pixels.
      Returns:
      panel's width
    • getX

      public int getX()
      Returns the drawing panel's x-coordinate on the screen.
      Returns:
      panel's x-coordinate
    • getY

      public int getY()
      Returns the drawing panel's y-coordinate on the screen.
      Returns:
      panel's y-coordinate
    • getZoom

      public int getZoom()
      Returns the drawing panel's current zoom factor. Initially this is 1 to indicate 100% zoom, the original size. A factor of 2 would indicate 200% zoom, and so on.
      Returns:
      zoom factor (default 1)
    • imageUpdate

      public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height)
      Internal method; notifies the panel when images are loaded and updated. This is a required method of ImageObserver interface. This is an internal method not meant to be called by clients.
      Specified by:
      imageUpdate in interface ImageObserver
      Parameters:
      img - internal method; do not call
      infoflags - internal method; do not call
      x - internal method; do not call
      y - internal method; do not call
      width - internal method; do not call
      height - internal method; do not call
    • loadImage

      public Image loadImage(File file)
      Loads an image from the given file on disk and returns it as an Image object.
      Parameters:
      file - the file to load
      Returns:
      loaded image object
      Throws:
      NullPointerException - if filename is null
      RuntimeException - if the given file is not found
    • loadImage

      public Image loadImage(String filename)
      Loads an image from the given file on disk and returns it as an Image object.
      Parameters:
      filename - name/path of the file to load
      Returns:
      loaded image object
      Throws:
      NullPointerException - if filename is null
      RuntimeException - if the given file is not found
    • onClick

      public void onClick(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse clicks. You can pass a lambda function here to be called when a mouse click event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onDrag

      public void onDrag(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse drags. You can pass a lambda function here to be called when a mouse drag event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onEnter

      public void onEnter(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse enters. You can pass a lambda function here to be called when a mouse enter event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onExit

      public void onExit(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse exits. You can pass a lambda function here to be called when a mouse exit event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onKeyDown

      public void onKeyDown(DrawingPanel.DPKeyEventHandler e)
      Adds an event handler for key presses. You can pass a lambda function here to be called when a key press event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onKeyUp

      public void onKeyUp(DrawingPanel.DPKeyEventHandler e)
      Adds an event handler for key releases. You can pass a lambda function here to be called when a key release event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onMouseClick

      public void onMouseClick(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse clicks. You can pass a lambda function here to be called when a mouse click event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onMouseDown

      public void onMouseDown(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse button down events. You can pass a lambda function here to be called when a mouse button down event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onMouseDrag

      public void onMouseDrag(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse drags. You can pass a lambda function here to be called when a mouse drag event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onMouseEnter

      public void onMouseEnter(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse enters. You can pass a lambda function here to be called when a mouse enter event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onMouseExit

      public void onMouseExit(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse exits. You can pass a lambda function here to be called when a mouse exit event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onMouseMove

      public void onMouseMove(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse movement. You can pass a lambda function here to be called when a mouse move event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onMouseUp

      public void onMouseUp(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse button up events. You can pass a lambda function here to be called when a mouse button up event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • onMove

      public void onMove(DrawingPanel.DPMouseEventHandler e)
      Adds an event handler for mouse movement. You can pass a lambda function here to be called when a mouse move event occurs.
      Parameters:
      e - event handler function to call
      Throws:
      NullPointerException - if event handler is null
    • save

      public void save(File file) throws IOException
      Takes the current contents of the drawing panel and writes them to the given file.
      Parameters:
      file - the file to save
      Throws:
      NullPointerException - if filename is null
      IOException - if the given file cannot be written
    • save

      public void save(String filename) throws IOException
      Takes the current contents of the drawing panel and writes them to the given file.
      Parameters:
      filename - name/path of the file to save
      Throws:
      NullPointerException - if filename is null
      IOException - if the given file cannot be written
    • saveAnimated

      public void saveAnimated(File file) throws IOException
      Takes the current contents of the drawing panel and writes them to the given file.
      Parameters:
      file - the file to save
      Throws:
      NullPointerException - if filename is null
      IOException - if the given file cannot be written
    • saveAnimated

      public void saveAnimated(String filename) throws IOException
      Takes the current contents of the drawing panel and writes them to the given file.
      Parameters:
      filename - name/path of the file to save
      Throws:
      NullPointerException - if filename is null
      IOException - if the given file cannot be written
    • setAlwaysOnTop

      public void setAlwaysOnTop(boolean alwaysOnTop)
      Sets whether the panel will always cover other windows (default false).
      Parameters:
      alwaysOnTop - true if the panel should always cover other windows
    • setAntiAlias

      public void setAntiAlias(boolean antiAlias)
      Sets whether the panel should use anti-aliased / smoothed graphics (default true).
      Parameters:
      antiAlias - true if the panel should be smoothed
    • setBackground

      public void setBackground(Color c)
      Sets the background color of the drawing panel to be the given color.
      Parameters:
      c - color to use as background
      Throws:
      NullPointerException - if color is null
    • setBackground

      public void setBackground(int rgb)
      Sets the background color of the drawing panel to be the color represented by the given RGB integer.
      Parameters:
      rgb - RGB integer to use as background color (full alpha assumed/applied)
    • setGridLines

      public void setGridLines(boolean gridLines)
      Enables or disables the drawing of grid lines on top of the image to help with debugging sizes and coordinates. By default the grid lines will be shown every 10 pixels in each dimension.
      Parameters:
      gridLines - whether to show grid lines (true) or not (false)
    • setGridLines

      public void setGridLines(boolean gridLines, int pxGap)
      Enables or disables the drawing of grid lines on top of the image to help with debugging sizes and coordinates. The grid lines will be shown every pxGap pixels in each dimension.
      Parameters:
      gridLines - whether to show grid lines (true) or not (false)
      pxGap - number of pixels between grid lines
    • setHeight

      public void setHeight(int height)
      Sets the drawing panel's height in pixels to the given value. After calling this method, the client must call getGraphics() again to get the new graphics context of the newly enlarged image buffer.
      Parameters:
      height - height, in pixels
      Throws:
      IllegalArgumentException - if height is negative or exceeds MAX_SIZE
    • setPixel

      public void setPixel(int x, int y, Color color)
      Sets the color of the pixel at the given x/y coordinate to be the given color. If the color is null, the call has no effect.
      Parameters:
      x - x-coordinate of pixel to set
      y - y-coordinate of pixel to set
      color - Color to set the pixel to use
      Throws:
      IllegalArgumentException - if x or y is out of bounds
      NullPointerException - if color is null
    • setPixel

      public void setPixel(int x, int y, int rgb)
      Sets the color of the pixel at the given x/y coordinate to be the color represented by the given RGB integer. The passed RGB integer's alpha value is ignored and a full alpha of 255 is always used here, to avoid common bugs with using a 0 value for alpha. See also: setPixel. See also: setPixelRGB.
      Parameters:
      x - x-coordinate of pixel to set
      y - y-coordinate of pixel to set
      rgb - RGB integer representing the color to set the pixel to use
      Throws:
      IllegalArgumentException - if x or y is out of bounds
    • setPixelRGB

      public void setPixelRGB(int x, int y, int rgb)
      Sets the color of the pixel at the given x/y coordinate to be the color represented by the given RGB integer. The passed RGB integer's alpha value is ignored and a full alpha of 255 is always used here, to avoid common bugs with using a 0 value for alpha. See also: setPixel.
      Parameters:
      x - x-coordinate of pixel to set
      y - y-coordinate of pixel to set
      rgb - RGB integer representing the color to set the pixel to use
      Throws:
      IllegalArgumentException - if x or y is out of bounds
    • setPixels

      public void setPixels(Color[][] pixels)
      Sets the colors of all pixels in this DrawingPanel to the colors in the given 2-D array of Color objects. The first index of the array is the y-coordinate, and the second index is the x-coordinate. So, for example, index [r][c] represents the RGB pixel data for the pixel at position (x=c, y=r). If the given array's dimensions do not match the width/height of the drawing panel, the panel is resized to match the array. If the pixel array is null or size 0, the call has no effect. If any rows or colors in the array are null, those pixels will be ignored. The 2-D array passed is assumed to be rectangular in length (not jagged).
      Parameters:
      pixels - 2D array of pixels (row-major)
      Throws:
      NullPointerException - if pixels array is null
    • setPixels

      public void setPixels(int[][] pixels)
      Sets the colors of all pixels in this DrawingPanel to the colors represented by the given 2-D array of RGB integers. The first index of the array is the y-coordinate, and the second index is the x-coordinate. So, for example, index [r][c] represents the RGB pixel data for the pixel at position (x=c, y=r). If the given array's dimensions do not match the width/height of the drawing panel, the panel is resized to match the array. If the pixel array is null or size 0, the call has no effect. The 2-D array passed is assumed to be rectangular in length (not jagged).
      Parameters:
      pixels - 2D array of pixels (row-major)
      Throws:
      NullPointerException - if pixels array is null
    • setPixelsRGB

      public void setPixelsRGB(int[][] pixels)
      Sets the colors of all pixels in this DrawingPanel to the colors represented by the given 2-D array of RGB integers. The first index of the array is the y-coordinate, and the second index is the x-coordinate. So, for example, index [r][c] represents the RGB pixel data for the pixel at position (x=c, y=r). If the given array's dimensions do not match the width/height of the drawing panel, the panel is resized to match the array. If the pixel array is null or size 0, the call has no effect. The 2-D array passed is assumed to be rectangular in length (not jagged).
      Parameters:
      pixels - 2D array of pixels (row-major)
      Throws:
      NullPointerException - if pixels array is null
    • setSize

      public void setSize(int width, int height)
      Sets the drawing panel's pixel size (width, height) to the given values. After calling this method, the client must call getGraphics() again to get the new graphics context of the newly enlarged image buffer.
      Parameters:
      width - width, in pixels
      height - height, in pixels
      Throws:
      IllegalArgumentException - if width/height is negative or exceeds MAX_SIZE
    • setVisible

      public void setVisible(boolean visible)
      Show or hide the drawing panel on the screen.
      Parameters:
      visible - true to show, false to hide
    • setWidth

      public void setWidth(int width)
      Sets the drawing panel's width in pixels to the given value. After calling this method, the client must call getGraphics() again to get the new graphics context of the newly enlarged image buffer.
      Parameters:
      width - width, in pixels
      Throws:
      IllegalArgumentException - if height is negative or exceeds MAX_SIZE
    • sleep

      public void sleep(int millis)
      Causes the program to pause for the given amount of time in milliseconds. This allows for animation by calling pause in a loop. If the DrawingPanel is not showing on the screen, has no effect.
      Parameters:
      millis - number of milliseconds to sleep
      Throws:
      IllegalArgumentException - if a negative number of ms is passed
    • toFront

      public void toFront()
      Moves the drawing panel window on top of other windows so it can be seen.
    • zoom

      public void zoom(int zoomFactor)
      Zooms the drawing panel in/out to the given factor. A zoom factor of 1, the default, indicates normal size. A zoom factor of 2 would indicate 200% size, and so on. The factor value passed should be at least 1; if not, 1 will be used.
      Parameters:
      zoomFactor - the zoom factor to use (1 or greater)