Class StdDraw

  • All Implemented Interfaces:
    ActionListener, KeyListener, MouseListener, MouseMotionListener, EventListener

    public final class StdDraw
    extends Object
    implements ActionListener, MouseListener, MouseMotionListener, KeyListener
    The StdDraw class provides static methods for creating drawings with your programs. It uses a simple graphics model that allows you to create drawings consisting of points, lines, squares, circles, and other geometric shapes in a window on your computer and to save the drawings to a file. Standard drawing also includes facilities for text, color, pictures, and animation, along with user interaction via the keyboard and mouse.

    Getting started. To use this class, you must have StdDraw.class in your Java classpath. If you used our autoinstaller, you should be all set. Otherwise, either download stdlib.jar and add to your Java classpath or download StdDraw.java and put a copy in your working directory.

    Now, cut-and-paste the following short program into your editor:

       public class TestStdDraw {
           public static void main(String[] args) {
               StdDraw.setPenRadius(0.05);
               StdDraw.setPenColor(StdDraw.BLUE);
               StdDraw.point(0.5, 0.5);
               StdDraw.setPenColor(StdDraw.MAGENTA);
               StdDraw.line(0.2, 0.2, 0.8, 0.2);
           }
       }
      
    If you compile and execute the program, you should see a window appear with a thick magenta line and a blue point. This program illustrates the two main types of methods in standard drawing—methods that draw geometric shapes and methods that control drawing parameters. The methods StdDraw.line() and StdDraw.point() draw lines and points; the methods StdDraw.setPenRadius() and StdDraw.setPenColor() control the line thickness and color.

    Points and lines. You can draw points and line segments with the following methods:

    The x- and y-coordinates must be in the drawing area (between 0 and 1 and by default) or the points and lines will not be visible.

    Squares, circles, rectangles, and ellipses. You can draw squares, circles, rectangles, and ellipses using the following methods:

    All of these methods take as arguments the location and size of the shape. The location is always specified by the x- and y-coordinates of its center. The size of a circle is specified by its radius and the size of an ellipse is specified by the lengths of its semi-major and semi-minor axes. The size of a square or rectangle is specified by its half-width or half-height. The convention for drawing squares and rectangles is parallel to those for drawing circles and ellipses, but may be unexpected to the uninitiated.

    The methods above trace outlines of the given shapes. The following methods draw filled versions:

    Circular arcs. You can draw circular arcs with the following method:

    The arc is from the circle centered at (x, y) of the specified radius. The arc extends from angle1 to angle2. By convention, the angles are polar (counterclockwise angle from the x-axis) and represented in degrees. For example, StdDraw.arc(0.0, 0.0, 1.0, 0, 90) draws the arc of the unit circle from 3 o'clock (0 degrees) to 12 o'clock (90 degrees).

    Polygons. You can draw polygons with the following methods:

    The points in the polygon are (x[i], y[i]). For example, the following code fragment draws a filled diamond with vertices (0.1, 0.2), (0.2, 0.3), (0.3, 0.2), and (0.2, 0.1):

       double[] x = { 0.1, 0.2, 0.3, 0.2 };
       double[] y = { 0.2, 0.3, 0.2, 0.1 };
       StdDraw.filledPolygon(x, y);
      

    Pen size. The pen is circular, so that when you set the pen radius to r and draw a point, you get a circle of radius r. Also, lines are of thickness 2r and have rounded ends. The default pen radius is 0.002 and is not affected by coordinate scaling. This default pen radius is about 1/500 the width of the default canvas, so that if you draw 200 points equally spaced along a horizontal or vertical line, you will be able to see individual circles, but if you draw 250 such points, the result will look like a line.

    For example, StdDraw.setPenRadius(0.01) makes the thickness of the lines and the size of the points to be five times the 0.002 default. To draw points with the minimum possible radius (one pixel on typical displays), set the pen radius to 0.0.

    Pen color. All geometric shapes (such as points, lines, and circles) are drawn using the current pen color. By default, it is black. You can change the pen color with the following methods:

    The first method allows you to specify colors using the RGB color system. This color picker is a convenient way to find a desired color.

    The second method allows you to specify colors using the Color data type, which is defined in Java's java.awt package. Standard drawing defines a number of predefined colors including BLACK, WHITE, RED, GREEN, and BLUE. For example, StdDraw.setPenColor(StdDraw.RED) sets the pen color to red.

    Window title. By default, the standard drawing window title is "Standard Draw". You can change the title with the following method:

    This sets the standard drawing window title to the specified string.

    Canvas size. By default, all drawing takes places in a 512-by-512 canvas. The canvas does not include the window title or window border. You can change the size of the canvas with the following method:

    This sets the canvas size to be width-by-height pixels. It also clears the current drawing using the default background color (white). Ordinarily, this method is called only once, at the very beginning of a program. For example, StdDraw.setCanvasSize(800, 800) sets the canvas size to be 800-by-800 pixels.

    Canvas scale and coordinate system. By default, all drawing takes places in the unit square, with (0, 0) at lower left and (1, 1) at upper right. You can change the default coordinate system with the following methods:

    The arguments are the coordinates of the minimum and maximum x- or y-coordinates that will appear in the canvas. For example, if you wish to use the default coordinate system but leave a small margin, you can call StdDraw.setScale(-.05, 1.05).

    These methods change the coordinate system for subsequent drawing commands; they do not affect previous drawings. These methods do not change the canvas size; so, if the x- and y-scales are different, squares will become rectangles and circles will become ellipses.

    Text. You can use the following methods to annotate your drawings with text:

    The first two methods write the specified text in the current font, centered at (x, y). The second method allows you to rotate the text. The last two methods either left- or right-align the text at (x, y).

    The default font is a Sans Serif font with point size 16. You can use the following method to change the font:

    To specify the font, you use the Font data type, which is defined in Java's java.awt package. This allows you to choose the face, size, and style of the font. For example, the following code fragment sets the font to Arial Bold, 60 point. The import statement allows you to refer to Font directly, without needing the fully qualified name java.awt.Font.

       import java.awt.Font;
       ...
       Font font = new Font("Arial", Font.BOLD, 60);
       StdDraw.setFont(font);
       StdDraw.text(0.5, 0.5, "Hello, World");
      

    Images. You can use the following methods to add images to your drawings:

    These methods draw the specified image, centered at (x, y). The image must be in a supported file format (typically JPEG, PNG, GIF, TIFF, and BMP). The image will display at its native size, independent of the coordinate system. Optionally, you can rotate the image a specified number of degrees counterclockwise or rescale it to fit snugly inside a bounding box.

    Saving to a file. You can save your image to a file using the File → Save menu option. You can also save a file programmatically using the following method:

    You can save the drawing to a file in a supported file format (typically JPEG, PNG, GIF, TIFF, and BMP).

    File formats. The StdDraw class supports reading and writing images to any of the file formats supported by javax.imageio (typically JPEG, PNG, GIF, TIFF, and BMP). The file extensions corresponding to JPEG, PNG, GIF, TIFF, and BMP, are .jpg, .png, .gif, .tif, and .bmp, respectively.

    We recommend using PNG for drawing that consist solely of geometric shapes and JPEG for drawings that contains pictures. The JPEG file format does not support transparent backgrounds.

    Clearing the canvas. To clear the entire drawing canvas, you can use the following methods:

    The first method clears the canvas to the default background color (white); the second method allows you to specify the background color. For example, StdDraw.clear(StdDraw.LIGHT_GRAY) clears the canvas to a shade of gray. To make the background transparent, call StdDraw.clear(StdDraw.TRANSPARENT).

    Computer animations and double buffering. Double buffering is one of the most powerful features of standard drawing, enabling computer animations. The following methods control the way in which objects are drawn:

    By default, double buffering is disabled, which means that as soon as you call a drawing method—such as point() or line()—the results appear on the screen.

    When double buffering is enabled by calling enableDoubleBuffering(), all drawing takes place on the offscreen canvas. The offscreen canvas is not displayed. Only when you call show() does your drawing get copied from the offscreen canvas to the onscreen canvas, where it is displayed in the standard drawing window. You can think of double buffering as collecting all of the lines, points, shapes, and text that you tell it to draw, and then drawing them all simultaneously, upon request.

    The most important use of double buffering is to produce computer animations, creating the illusion of motion by rapidly displaying static drawings. To produce an animation, repeat the following four steps:

    • Clear the offscreen canvas.
    • Draw objects on the offscreen canvas.
    • Copy the offscreen canvas to the onscreen canvas.
    • Wait for a short while.

    The clear(), show(), and pause(int t) methods support the first, third, and fourth of these steps, respectively.

    For example, this code fragment animates two balls moving in a circle.

       StdDraw.setScale(-2.0, +2.0);
       StdDraw.enableDoubleBuffering();
    
       for (double t = 0.0; true; t += 0.02) {
           double x = Math.sin(t);
           double y = Math.cos(t);
           StdDraw.clear();
           StdDraw.filledCircle(x, y, 0.1);
           StdDraw.filledCircle(-x, -y, 0.1);
           StdDraw.show();
           StdDraw.pause(20);
       }
      
    Without double buffering, the balls would flicker as they move.

    Keyboard and mouse inputs. Standard drawing has very basic support for keyboard and mouse input. It is much less powerful than most user interface libraries provide, but also much simpler. You can use the following methods to intercept mouse events:

    The first method tells you whether a mouse button is currently being pressed. The last two methods tells you the x- and y-coordinates of the mouse's current position, using the same coordinate system as the canvas (the unit square, by default). You should use these methods in an animation loop that waits a short while before trying to poll the mouse for its current state. You can use the following methods to intercept keyboard events:

    If the user types lots of keys, they will be saved in a list until you process them. The first method tells you whether the user has typed a key (that your program has not yet processed). The second method returns the next key that the user typed (that your program has not yet processed) and removes it from the list of saved keystrokes. The third method tells you whether a key is currently being pressed.

    Accessing control parameters. You can use the following methods to access the current pen color, pen radius, and font:

    These methods are useful when you want to temporarily change a control parameter and, later, reset it back to its original value.

    Corner cases. Here are some corner cases.

    • Drawing an object outside (or partly outside) the canvas is permitted. However, only the part of the object that appears inside the canvas will be visible.
    • Due to floating-point issues, an object drawn with an x- or y-coordinate that is way outside the canvas (such as the line segment from (0.5, –10^308) to (0.5, 10^308) may not be visible even in the part of the canvas where it should be.
    • Any method that is passed a null argument will throw an IllegalArgumentException.
    • Any method that is passed a Double.NaN, Double.POSITIVE_INFINITY, or Double.NEGATIVE_INFINITY argument will throw an IllegalArgumentException.

    Performance tricks. Standard drawing is capable of drawing large amounts of data. Here are a few tricks and tips:

    • Use double buffering for static drawing with a large number of objects. That is, call enableDoubleBuffering() before the sequence of drawing commands and call show() afterwards. Incrementally displaying a complex drawing while it is being created can be intolerably inefficient on many computer systems.
    • When drawing computer animations, call show() only once per frame, not after drawing each individual object.
    • If you call picture() multiple times with the same filename, Java will cache the image, so you do not incur the cost of reading from a file each time.

    Known bugs and issues.

    • The picture() methods may not draw the portion of the image that is inside the canvas if the center point (x, y) is outside the canvas. This bug appears only on some systems.

    Reference. For additional documentation, see Section 1.5 of Computer Science: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne.

    Author:
    Robert Sedgewick, Kevin Wayne
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static Color AQUA
      The color aqua (0, 255, 255).
      static Color BLACK
      The color black (0, 0, 0).
      static Color BLUE
      The color blue (0, 0, 255).
      static Color BOOK_BLUE
      The shade of blue used in Introduction to Programming in Java.
      static Color BOOK_LIGHT_BLUE
      The shade of light blue used in Introduction to Programming in Java.
      static Color BOOK_RED
      The shade of red used in Algorithms, 4th edition.
      static Color CYAN
      The color cyan (0, 255, 255).
      static Color DARK_GRAY
      The color dark gray (64, 64, 64).
      static Color FUSCIA
      The color fuscia (255, 0, 255).
      static Color GRAY
      The color gray (128, 128, 128).
      static Color GREEN
      The color green (0, 128, 0).
      static Color LIGHT_GRAY
      The color light gray (192, 192, 192).
      static Color LIME
      The color lime (0, 255, 0).
      static Color MAGENTA
      The color magenta (255, 0, 255).
      static Color MAROON
      The color maroon (128, 0, 0).
      static Color NAVY
      The color navy (0, 0, 128).
      static Color OLIVE
      The color olive (128, 128, 0).
      static Color ORANGE
      The color orange (255, 200, 0).
      static Color PINK
      The color pink (255, 175, 175).
      static Color PRINCETON_ORANGE
      The shade of orange used in Princeton University's identity.
      static Color PURPLE
      The color purple (128, 0, 128).
      static Color RED
      The color red (255, 0, 0).
      static Color SILVER
      The color silver (192, 192, 192).
      static Color TEAL
      The color teal (0, 128, 128).
      static Color TRANSPARENT
      A 100% transparent color, for a transparent background.
      static Color WHITE
      The color white (255, 255, 255).
      static Color YELLOW
      The color yellow (255, 255, 0).
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void actionPerformed​(ActionEvent event)
      This method cannot be called directly.
      static void arc​(double x, double y, double radius, double angle1, double angle2)
      Draws a circular arc of the specified radius, centered at (x, y), from angle1 to angle2 (in degrees).
      static void circle​(double x, double y, double radius)
      Draws a circle of the specified radius, centered at (x, y).
      static void clear()
      Clears the screen using the default background color (white).
      static void clear​(Color color)
      Clears the screen using the specified background color.
      static void close()
      Closes the standard drawing window.
      static void disableDoubleBuffering()
      Disables double buffering.
      static void ellipse​(double x, double y, double semiMajorAxis, double semiMinorAxis)
      Draws an ellipse with the specified semimajor and semiminor axes, centered at (x, y).
      static void enableDoubleBuffering()
      Enables double buffering.
      static void filledCircle​(double x, double y, double radius)
      Draws a filled circle of the specified radius, centered at (x, y).
      static void filledEllipse​(double x, double y, double semiMajorAxis, double semiMinorAxis)
      Draws a filled ellipse with the specified semimajor and semiminor axes, centered at (x, y).
      static void filledPolygon​(double[] x, double[] y)
      Draws a filled polygon with the vertices (x0, y0), (x1, y1), ..., (xn–1, yn–1).
      static void filledRectangle​(double x, double y, double halfWidth, double halfHeight)
      Draws a filled rectangle of the specified size, centered at (x, y).
      static void filledSquare​(double x, double y, double halfLength)
      Draws a filled square of the specified size, centered at (x, y).
      static Color getBackgroundColor()
      Returns the current background color.
      static Font getFont()
      Returns the current font.
      static Color getPenColor()
      Returns the current pen color.
      static double getPenRadius()
      Returns the current pen radius.
      static boolean hasNextKeyTyped()
      Returns true if the user has typed a key (that has not yet been processed).
      static boolean isKeyPressed​(int keycode)
      Returns true if the given key is being pressed.
      static boolean isMousePressed()
      Returns true if the mouse is being pressed.
      void keyPressed​(KeyEvent event)
      This method cannot be called directly.
      void keyReleased​(KeyEvent event)
      This method cannot be called directly.
      void keyTyped​(KeyEvent event)
      This method cannot be called directly.
      static void line​(double x0, double y0, double x1, double y1)
      Draws a line segment between (x0, y0) and (x1, y1).
      static void main​(String[] args)
      Test client.
      void mouseClicked​(MouseEvent event)
      This method cannot be called directly.
      void mouseDragged​(MouseEvent event)
      This method cannot be called directly.
      void mouseEntered​(MouseEvent event)
      This method cannot be called directly.
      void mouseExited​(MouseEvent event)
      This method cannot be called directly.
      void mouseMoved​(MouseEvent event)
      This method cannot be called directly.
      void mousePressed​(MouseEvent event)
      This method cannot be called directly.
      void mouseReleased​(MouseEvent event)
      This method cannot be called directly.
      static double mouseX()
      Returns the x-coordinate of the mouse.
      static double mouseY()
      Returns the y-coordinate of the mouse.
      static char nextKeyTyped()
      Returns the next key that was typed by the user (that your program has not already processed).
      static void pause​(int t)
      Pauses for t milliseconds.
      static void picture​(double x, double y, String filename)
      Draws the specified image centered at (x, y).
      static void picture​(double x, double y, String filename, double degrees)
      Draws the specified image centered at (x, y), rotated given number of degrees.
      static void picture​(double x, double y, String filename, double scaledWidth, double scaledHeight)
      Draws the specified image centered at (x, y), rescaled to the specified bounding box.
      static void picture​(double x, double y, String filename, double scaledWidth, double scaledHeight, double degrees)
      Draws the specified image centered at (x, y), rotated given number of degrees, and rescaled to the specified bounding box.
      static void point​(double x, double y)
      Draws a point centered at (x, y).
      static void polygon​(double[] x, double[] y)
      Draws a polygon with the vertices (x0, y0), (x1, y1), ..., (xn–1, yn–1).
      static void rectangle​(double x, double y, double halfWidth, double halfHeight)
      Draws a rectangle of the specified size, centered at (x, y).
      static void save​(String filename)
      Saves the drawing to a file in a supported file format (typically JPEG, PNG, GIF, TIFF, and BMP).
      static void setCanvasSize()
      Sets the canvas (drawing area) to be 512-by-512 pixels.
      static void setCanvasSize​(int canvasWidth, int canvasHeight)
      Sets the canvas (drawing area) to be width-by-height pixels.
      static void setFont()
      Sets the font to the default font (sans serif, 16 point).
      static void setFont​(Font font)
      Sets the font to the specified value.
      static void setPenColor()
      Sets the pen color to the default color (black).
      static void setPenColor​(int red, int green, int blue)
      Sets the pen color to the specified RGB color.
      static void setPenColor​(Color color)
      Sets the pen color to the specified color.
      static void setPenRadius()
      Sets the pen size to the default size (0.002).
      static void setPenRadius​(double radius)
      Sets the radius of the pen to the specified size.
      static void setScale()
      Sets both the x-scale and y-scale to the default range (between 0.0 and 1.0).
      static void setScale​(double min, double max)
      Sets both the x-scale and y-scale to the (same) specified range.
      static void setTitle​(String title)
      Sets the title of the standard drawing window to the specified string.
      static void setVisible​(boolean isVisible)
      Makes the drawing window visible or invisible.
      static void setXscale()
      Sets the x-scale to the default range (between 0.0 and 1.0).
      static void setXscale​(double min, double max)
      Sets the x-scale to the specified range.
      static void setYscale()
      Sets the y-scale to the default range (between 0.0 and 1.0).
      static void setYscale​(double min, double max)
      Sets the y-scale to the specified range.
      static void show()
      Copies offscreen buffer to onscreen buffer.
      static void square​(double x, double y, double halfLength)
      Draws a square of the specified size, centered at (x, y).
      static void text​(double x, double y, String text)
      Writes the given text string in the current font, centered at (x, y).
      static void text​(double x, double y, String text, double degrees)
      Writes the given text string in the current font, centered at (x, y) and rotated by the specified number of degrees.
      static void textLeft​(double x, double y, String text)
      Writes the given text string in the current font, left-aligned at (x, y).
      static void textRight​(double x, double y, String text)
      Writes the given text string in the current font, right-aligned at (x, y).
    • Field Detail

      • AQUA

        public static final Color AQUA
        The color aqua (0, 255, 255).
      • BLACK

        public static final Color BLACK
        The color black (0, 0, 0).
      • BLUE

        public static final Color BLUE
        The color blue (0, 0, 255).
      • CYAN

        public static final Color CYAN
        The color cyan (0, 255, 255).
      • FUSCIA

        public static final Color FUSCIA
        The color fuscia (255, 0, 255).
      • DARK_GRAY

        public static final Color DARK_GRAY
        The color dark gray (64, 64, 64).
      • GRAY

        public static final Color GRAY
        The color gray (128, 128, 128).
      • GREEN

        public static final Color GREEN
        The color green (0, 128, 0).
      • LIGHT_GRAY

        public static final Color LIGHT_GRAY
        The color light gray (192, 192, 192).
      • LIME

        public static final Color LIME
        The color lime (0, 255, 0).
      • MAGENTA

        public static final Color MAGENTA
        The color magenta (255, 0, 255).
      • MAROON

        public static final Color MAROON
        The color maroon (128, 0, 0).
      • NAVY

        public static final Color NAVY
        The color navy (0, 0, 128).
      • OLIVE

        public static final Color OLIVE
        The color olive (128, 128, 0).
      • ORANGE

        public static final Color ORANGE
        The color orange (255, 200, 0).
      • PINK

        public static final Color PINK
        The color pink (255, 175, 175).
      • PURPLE

        public static final Color PURPLE
        The color purple (128, 0, 128).
      • RED

        public static final Color RED
        The color red (255, 0, 0).
      • SILVER

        public static final Color SILVER
        The color silver (192, 192, 192).
      • TEAL

        public static final Color TEAL
        The color teal (0, 128, 128).
      • WHITE

        public static final Color WHITE
        The color white (255, 255, 255).
      • YELLOW

        public static final Color YELLOW
        The color yellow (255, 255, 0).
      • TRANSPARENT

        public static final Color TRANSPARENT
        A 100% transparent color, for a transparent background.
      • BOOK_BLUE

        public static final Color BOOK_BLUE
        The shade of blue used in Introduction to Programming in Java. It is Pantone 300U. The RGB values are approximately (9, 90, 166).
      • BOOK_LIGHT_BLUE

        public static final Color BOOK_LIGHT_BLUE
        The shade of light blue used in Introduction to Programming in Java. The RGB values are approximately (103, 198, 243).
      • BOOK_RED

        public static final Color BOOK_RED
        The shade of red used in Algorithms, 4th edition. It is Pantone 1805U. The RGB values are approximately (150, 35, 31).
      • PRINCETON_ORANGE

        public static final Color PRINCETON_ORANGE
        The shade of orange used in Princeton University's identity. It is PMS 158. The RGB values are approximately (245, 128, 37).
    • Method Detail

      • setVisible

        public static void setVisible​(boolean isVisible)
        Makes the drawing window visible or invisible.
        Parameters:
        isVisible - if true, makes the drawing window visible, otherwise hides the drawing window.
      • setCanvasSize

        public static void setCanvasSize()
        Sets the canvas (drawing area) to be 512-by-512 pixels. This also clears the current drawing using the default background color (white). Ordinarily, this method is called once, at the very beginning of a program.
      • setCanvasSize

        public static void setCanvasSize​(int canvasWidth,
                                         int canvasHeight)
        Sets the canvas (drawing area) to be width-by-height pixels. This also clears the current drawing using the default background color (white). Ordinarily, this method is called once, at the very beginning of a program.
        Parameters:
        canvasWidth - the width as a number of pixels
        canvasHeight - the height as a number of pixels
        Throws:
        IllegalArgumentException - unless both canvasWidth and canvasHeight are positive
      • close

        public static void close()
        Closes the standard drawing window. This allows the client program to terminate instead of requiring the user to close the standard drawing window manually. Drawing after calling this method will restore the previous window state.
      • setTitle

        public static void setTitle​(String title)
        Sets the title of the standard drawing window to the specified string.
        Parameters:
        title - the title
        Throws:
        IllegalArgumentException - if title is null
      • setXscale

        public static void setXscale()
        Sets the x-scale to the default range (between 0.0 and 1.0).
      • setYscale

        public static void setYscale()
        Sets the y-scale to the default range (between 0.0 and 1.0).
      • setScale

        public static void setScale()
        Sets both the x-scale and y-scale to the default range (between 0.0 and 1.0).
      • setXscale

        public static void setXscale​(double min,
                                     double max)
        Sets the x-scale to the specified range.
        Parameters:
        min - the minimum value of the x-scale
        max - the maximum value of the x-scale
        Throws:
        IllegalArgumentException - if (max == min)
        IllegalArgumentException - if either min or max is either NaN or infinite
      • setYscale

        public static void setYscale​(double min,
                                     double max)
        Sets the y-scale to the specified range.
        Parameters:
        min - the minimum value of the y-scale
        max - the maximum value of the y-scale
        Throws:
        IllegalArgumentException - if (max == min)
        IllegalArgumentException - if either min or max is either NaN or infinite
      • setScale

        public static void setScale​(double min,
                                    double max)
        Sets both the x-scale and y-scale to the (same) specified range.
        Parameters:
        min - the minimum value of the x- and y-scales
        max - the maximum value of the x- and y-scales
        Throws:
        IllegalArgumentException - if (max == min)
        IllegalArgumentException - if either min or max is either NaN or infinite
      • clear

        public static void clear()
        Clears the screen using the default background color (white).
      • clear

        public static void clear​(Color color)
        Clears the screen using the specified background color. To make the background transparent, use StdDraw.TRANSPARENT.
        Parameters:
        color - the color to make the background
        Throws:
        IllegalArgumentException - if color is null
      • getPenRadius

        public static double getPenRadius()
        Returns the current pen radius.
        Returns:
        the current value of the pen radius
      • setPenRadius

        public static void setPenRadius()
        Sets the pen size to the default size (0.002). The pen is circular, so that lines have rounded ends, and when you set the pen radius and draw a point, you get a circle of the specified radius. The pen radius is not affected by coordinate scaling.
      • setPenRadius

        public static void setPenRadius​(double radius)
        Sets the radius of the pen to the specified size. The pen is circular, so that lines have rounded ends, and when you set the pen radius and draw a point, you get a circle of the specified radius. The pen radius is not affected by coordinate scaling.
        Parameters:
        radius - the radius of the pen
        Throws:
        IllegalArgumentException - if radius is negative, NaN, or infinite
      • getPenColor

        public static Color getPenColor()
        Returns the current pen color.
        Returns:
        the current pen color
      • getBackgroundColor

        public static Color getBackgroundColor()
        Returns the current background color.
        Returns:
        the current background color
      • setPenColor

        public static void setPenColor()
        Sets the pen color to the default color (black).
      • setPenColor

        public static void setPenColor​(Color color)
        Sets the pen color to the specified color.

        There are a number predefined pen colors, such as StdDraw.BLACK, StdDraw.WHITE, StdDraw.RED, StdDraw.GREEN, and StdDraw.BLUE.

        Parameters:
        color - the color to make the pen
        Throws:
        IllegalArgumentException - if color is null
      • setPenColor

        public static void setPenColor​(int red,
                                       int green,
                                       int blue)
        Sets the pen color to the specified RGB color.
        Parameters:
        red - the amount of red (between 0 and 255)
        green - the amount of green (between 0 and 255)
        blue - the amount of blue (between 0 and 255)
        Throws:
        IllegalArgumentException - if red, green, or blue is outside its prescribed range
      • getFont

        public static Font getFont()
        Returns the current font.
        Returns:
        the current font
      • setFont

        public static void setFont()
        Sets the font to the default font (sans serif, 16 point).
      • setFont

        public static void setFont​(Font font)
        Sets the font to the specified value.
        Parameters:
        font - the font
        Throws:
        IllegalArgumentException - if font is null
      • line

        public static void line​(double x0,
                                double y0,
                                double x1,
                                double y1)
        Draws a line segment between (x0, y0) and (x1, y1).
        Parameters:
        x0 - the x-coordinate of one endpoint
        y0 - the y-coordinate of one endpoint
        x1 - the x-coordinate of the other endpoint
        y1 - the y-coordinate of the other endpoint
        Throws:
        IllegalArgumentException - if any coordinate is either NaN or infinite
      • point

        public static void point​(double x,
                                 double y)
        Draws a point centered at (x, y). The point is a filled circle whose radius is equal to the pen radius. To draw a single-pixel point, first set the pen radius to 0.
        Parameters:
        x - the x-coordinate of the point
        y - the y-coordinate of the point
        Throws:
        IllegalArgumentException - if either x or y is either NaN or infinite
      • circle

        public static void circle​(double x,
                                  double y,
                                  double radius)
        Draws a circle of the specified radius, centered at (x, y).
        Parameters:
        x - the x-coordinate of the center of the circle
        y - the y-coordinate of the center of the circle
        radius - the radius of the circle
        Throws:
        IllegalArgumentException - if radius is negative
        IllegalArgumentException - if any argument is either NaN or infinite
      • filledCircle

        public static void filledCircle​(double x,
                                        double y,
                                        double radius)
        Draws a filled circle of the specified radius, centered at (x, y).
        Parameters:
        x - the x-coordinate of the center of the circle
        y - the y-coordinate of the center of the circle
        radius - the radius of the circle
        Throws:
        IllegalArgumentException - if radius is negative
        IllegalArgumentException - if any argument is either NaN or infinite
      • ellipse

        public static void ellipse​(double x,
                                   double y,
                                   double semiMajorAxis,
                                   double semiMinorAxis)
        Draws an ellipse with the specified semimajor and semiminor axes, centered at (x, y).
        Parameters:
        x - the x-coordinate of the center of the ellipse
        y - the y-coordinate of the center of the ellipse
        semiMajorAxis - is the semimajor axis of the ellipse
        semiMinorAxis - is the semiminor axis of the ellipse
        Throws:
        IllegalArgumentException - if either semiMajorAxis or semiMinorAxis is negative
        IllegalArgumentException - if any argument is either NaN or infinite
      • filledEllipse

        public static void filledEllipse​(double x,
                                         double y,
                                         double semiMajorAxis,
                                         double semiMinorAxis)
        Draws a filled ellipse with the specified semimajor and semiminor axes, centered at (x, y).
        Parameters:
        x - the x-coordinate of the center of the ellipse
        y - the y-coordinate of the center of the ellipse
        semiMajorAxis - is the semimajor axis of the ellipse
        semiMinorAxis - is the semiminor axis of the ellipse
        Throws:
        IllegalArgumentException - if either semiMajorAxis or semiMinorAxis is negative
        IllegalArgumentException - if any argument is either NaN or infinite
      • arc

        public static void arc​(double x,
                               double y,
                               double radius,
                               double angle1,
                               double angle2)
        Draws a circular arc of the specified radius, centered at (x, y), from angle1 to angle2 (in degrees).
        Parameters:
        x - the x-coordinate of the center of the circle
        y - the y-coordinate of the center of the circle
        radius - the radius of the circle
        angle1 - the starting angle. 0 would mean an arc beginning at 3 o'clock.
        angle2 - the angle at the end of the arc. For example, if you want a 90 degree arc, then angle2 should be angle1 + 90.
        Throws:
        IllegalArgumentException - if radius is negative
        IllegalArgumentException - if any argument is either NaN or infinite
      • square

        public static void square​(double x,
                                  double y,
                                  double halfLength)
        Draws a square of the specified size, centered at (x, y).
        Parameters:
        x - the x-coordinate of the center of the square
        y - the y-coordinate of the center of the square
        halfLength - one half the length of any side of the square
        Throws:
        IllegalArgumentException - if halfLength is negative
        IllegalArgumentException - if any argument is either NaN or infinite
      • filledSquare

        public static void filledSquare​(double x,
                                        double y,
                                        double halfLength)
        Draws a filled square of the specified size, centered at (x, y).
        Parameters:
        x - the x-coordinate of the center of the square
        y - the y-coordinate of the center of the square
        halfLength - one half the length of any side of the square
        Throws:
        IllegalArgumentException - if halfLength is negative
        IllegalArgumentException - if any argument is either NaN or infinite
      • rectangle

        public static void rectangle​(double x,
                                     double y,
                                     double halfWidth,
                                     double halfHeight)
        Draws a rectangle of the specified size, centered at (x, y).
        Parameters:
        x - the x-coordinate of the center of the rectangle
        y - the y-coordinate of the center of the rectangle
        halfWidth - one half the width of the rectangle
        halfHeight - one half the height of the rectangle
        Throws:
        IllegalArgumentException - if either halfWidth or halfHeight is negative
        IllegalArgumentException - if any argument is either NaN or infinite
      • filledRectangle

        public static void filledRectangle​(double x,
                                           double y,
                                           double halfWidth,
                                           double halfHeight)
        Draws a filled rectangle of the specified size, centered at (x, y).
        Parameters:
        x - the x-coordinate of the center of the rectangle
        y - the y-coordinate of the center of the rectangle
        halfWidth - one half the width of the rectangle
        halfHeight - one half the height of the rectangle
        Throws:
        IllegalArgumentException - if either halfWidth or halfHeight is negative
        IllegalArgumentException - if any argument is either NaN or infinite
      • polygon

        public static void polygon​(double[] x,
                                   double[] y)
        Draws a polygon with the vertices (x0, y0), (x1, y1), ..., (xn–1, yn–1).
        Parameters:
        x - an array of all the x-coordinates of the polygon
        y - an array of all the y-coordinates of the polygon
        Throws:
        IllegalArgumentException - unless x[] and y[] are of the same length
        IllegalArgumentException - if any coordinate is either NaN or infinite
        IllegalArgumentException - if either x[] or y[] is null
      • filledPolygon

        public static void filledPolygon​(double[] x,
                                         double[] y)
        Draws a filled polygon with the vertices (x0, y0), (x1, y1), ..., (xn–1, yn–1).
        Parameters:
        x - an array of all the x-coordinates of the polygon
        y - an array of all the y-coordinates of the polygon
        Throws:
        IllegalArgumentException - unless x[] and y[] are of the same length
        IllegalArgumentException - if any coordinate is either NaN or infinite
        IllegalArgumentException - if either x[] or y[] is null
      • picture

        public static void picture​(double x,
                                   double y,
                                   String filename)
        Draws the specified image centered at (x, y). The supported image formats are typically JPEG, PNG, GIF, TIFF, and BMP. As an optimization, the picture is cached, so there is no performance penalty for redrawing the same image multiple times (e.g., in an animation). However, if you change the picture file after drawing it, subsequent calls will draw the original picture.
        Parameters:
        x - the center x-coordinate of the image
        y - the center y-coordinate of the image
        filename - the name of the image/picture, e.g., "ball.gif"
        Throws:
        IllegalArgumentException - if the image filename is invalid
        IllegalArgumentException - if either x or y is either NaN or infinite
      • picture

        public static void picture​(double x,
                                   double y,
                                   String filename,
                                   double degrees)
        Draws the specified image centered at (x, y), rotated given number of degrees. The supported image formats are typically JPEG, PNG, GIF, TIFF, and BMP.
        Parameters:
        x - the center x-coordinate of the image
        y - the center y-coordinate of the image
        filename - the name of the image/picture, e.g., "ball.gif"
        degrees - is the number of degrees to rotate counterclockwise
        Throws:
        IllegalArgumentException - if the image filename is invalid
        IllegalArgumentException - if x, y, degrees is NaN or infinite
        IllegalArgumentException - if filename is null
      • picture

        public static void picture​(double x,
                                   double y,
                                   String filename,
                                   double scaledWidth,
                                   double scaledHeight)
        Draws the specified image centered at (x, y), rescaled to the specified bounding box. The supported image formats are typically JPEG, PNG, GIF, TIFF, and BMP.
        Parameters:
        x - the center x-coordinate of the image
        y - the center y-coordinate of the image
        filename - the name of the image/picture, e.g., "ball.gif"
        scaledWidth - the width of the scaled image (in screen coordinates)
        scaledHeight - the height of the scaled image (in screen coordinates)
        Throws:
        IllegalArgumentException - if either scaledWidth or scaledHeight is negative
        IllegalArgumentException - if the image filename is invalid
        IllegalArgumentException - if x or y is either NaN or infinite
        IllegalArgumentException - if filename is null
      • picture

        public static void picture​(double x,
                                   double y,
                                   String filename,
                                   double scaledWidth,
                                   double scaledHeight,
                                   double degrees)
        Draws the specified image centered at (x, y), rotated given number of degrees, and rescaled to the specified bounding box. The supported image formats are typically JPEG, PNG, GIF, TIFF, and BMP.
        Parameters:
        x - the center x-coordinate of the image
        y - the center y-coordinate of the image
        filename - the name of the image/picture, e.g., "ball.gif"
        scaledWidth - the width of the scaled image (in screen coordinates)
        scaledHeight - the height of the scaled image (in screen coordinates)
        degrees - is the number of degrees to rotate counterclockwise
        Throws:
        IllegalArgumentException - if either scaledWidth or scaledHeight is negative
        IllegalArgumentException - if the image filename is invalid
      • text

        public static void text​(double x,
                                double y,
                                String text)
        Writes the given text string in the current font, centered at (x, y).
        Parameters:
        x - the center x-coordinate of the text
        y - the center y-coordinate of the text
        text - the text to write
        Throws:
        IllegalArgumentException - if text is null
        IllegalArgumentException - if x or y is either NaN or infinite
      • text

        public static void text​(double x,
                                double y,
                                String text,
                                double degrees)
        Writes the given text string in the current font, centered at (x, y) and rotated by the specified number of degrees.
        Parameters:
        x - the center x-coordinate of the text
        y - the center y-coordinate of the text
        text - the text to write
        degrees - is the number of degrees to rotate counterclockwise
        Throws:
        IllegalArgumentException - if text is null
        IllegalArgumentException - if x, y, or degrees is either NaN or infinite
      • textLeft

        public static void textLeft​(double x,
                                    double y,
                                    String text)
        Writes the given text string in the current font, left-aligned at (x, y).
        Parameters:
        x - the x-coordinate of the text
        y - the y-coordinate of the text
        text - the text
        Throws:
        IllegalArgumentException - if text is null
        IllegalArgumentException - if x or y is either NaN or infinite
      • textRight

        public static void textRight​(double x,
                                     double y,
                                     String text)
        Writes the given text string in the current font, right-aligned at (x, y).
        Parameters:
        x - the x-coordinate of the text
        y - the y-coordinate of the text
        text - the text to write
        Throws:
        IllegalArgumentException - if text is null
        IllegalArgumentException - if x or y is either NaN or infinite
      • pause

        public static void pause​(int t)
        Pauses for t milliseconds. This method is intended to support computer animations.
        Parameters:
        t - number of milliseconds
        Throws:
        IllegalArgumentException - if t is negative
      • show

        public static void show()
        Copies offscreen buffer to onscreen buffer. There is no reason to call this method unless double buffering is enabled.
      • enableDoubleBuffering

        public static void enableDoubleBuffering()
        Enables double buffering. All subsequent calls to drawing methods such as line(), circle(), and square() will be deferred until the next call to show(). Useful for animations.
      • disableDoubleBuffering

        public static void disableDoubleBuffering()
        Disables double buffering. All subsequent calls to drawing methods such as line(), circle(), and square() will be displayed on screen when called. This is the default.
      • isMousePressed

        public static boolean isMousePressed()
        Returns true if the mouse is being pressed.
        Returns:
        true if the mouse is being pressed; false otherwise
      • mouseX

        public static double mouseX()
        Returns the x-coordinate of the mouse.
        Returns:
        the x-coordinate of the mouse
      • mouseY

        public static double mouseY()
        Returns the y-coordinate of the mouse.
        Returns:
        y-coordinate of the mouse
      • hasNextKeyTyped

        public static boolean hasNextKeyTyped()
        Returns true if the user has typed a key (that has not yet been processed).
        Returns:
        true if the user has typed a key (that has not yet been processed by nextKeyTyped(); false otherwise
      • nextKeyTyped

        public static char nextKeyTyped()
        Returns the next key that was typed by the user (that your program has not already processed). This method should be preceded by a call to hasNextKeyTyped() to ensure that there is a next key to process. This method returns a Unicode character corresponding to the key typed (such as 'a' or 'A'). It cannot identify action keys (such as F1 and arrow keys) or modifier keys (such as control).
        Returns:
        the next key typed by the user (that your program has not already processed).
        Throws:
        NoSuchElementException - if there is no remaining key
      • isKeyPressed

        public static boolean isKeyPressed​(int keycode)
        Returns true if the given key is being pressed.

        This method takes the keycode (corresponding to a physical key) as an argument. It can handle action keys (such as F1 and arrow keys) and modifier keys (such as shift and control). See KeyEvent for a description of key codes.

        Parameters:
        keycode - the key to check if it is being pressed
        Returns:
        true if keycode is currently being pressed; false otherwise
      • keyTyped

        public void keyTyped​(KeyEvent event)
        This method cannot be called directly.
        Specified by:
        keyTyped in interface KeyListener
      • keyPressed

        public void keyPressed​(KeyEvent event)
        This method cannot be called directly.
        Specified by:
        keyPressed in interface KeyListener
      • keyReleased

        public void keyReleased​(KeyEvent event)
        This method cannot be called directly.
        Specified by:
        keyReleased in interface KeyListener
      • main

        public static void main​(String[] args)
        Test client.
        Parameters:
        args - the command-line arguments