Skip to main content
Engineering LibreTexts

2.2: Drawing Shapes with the Graphics Object (Optional)

  • Page ID
    15064
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    All of the instance methods of the String class that we examined return values. The length() method return an int value, and the concat() method returned a String. It is also very common for classes to define instance methods that perform actions but do not return a value. The Graphics object, g, that appears in Chapter 1’s HelloWorldSwing is one example. The program is reproduced in Figure [fig-helloworld2]

     /** File: HelloWorldSwing program */
    
    import javax.swing.JFrame; // Import class names
    import java.awt.Graphics;
    import java.awt.Canvas;
    
    public class HelloWorldCanvas extends Canvas // Class header
    {                                            
        // Start of body
        public void paint(Graphics g)           
            // The paint method
        {
            g.drawString("Hello, World!", 10, 10);
        }  // End of paint
    
        public static void main(String[] args){
            HelloWorldCanvas c = new HelloWorldCanvas();
            JFrame f = new JFrame();
            f.add(c);
            f.setSize(150,50);
            f.setVisible(true);
        }
    }  // End of HelloWorldCanvas

    At this point we will not worry about the language features that enable the paint() method to draw on the Java Swing window. We will focus instead on the information needed to make good use of the g.drawString() method. The first thing you should know is that, when the paint() method is executed, its parameter, g, refers to an instance of the Graphics class. Unlike our other examples involving variables that refer to objects, in this case there is no need to use a constructor to create an object of type Graphics. We can assume g already refers to such an object.

    We already know that the statement

    g.drawString("Hello, World!",10,10);   

    displays the String “Hello, World!” in the program window. More generally, if str is a literal String value or a reference to a String object and x and y are literal int values or int variables then

    g.drawString(str,x,y) 

    displays the String str from left to right in the program window beginning at a point which is x pixels from the left edge of the window and y pixels down from the top edge of the window. In a graphics window, the point with coordinates (0,0) is at the top-left corner. The horizontal axis grows positively from left to right. The vertical axis grows positively from top to bottom (Fig. 2.6).

    (A pixel is a dot on the console window that can be set to a certain color.) Notice that increasing the value of y will cause str to be displayed lower. This is the opposite of the usual \(x\) and \(y\) coordinate system used in mathematics where increasing the \(y\) value designates a higher point.

    With this information about g.drawString(), we can calculate where to display any message in the program window. For example, if we wish to display the message “Welcome to Java” 25 pixels below where “Hello, World!” is displayed we could use the statements

    g.drawString("Hello, World!",10,10);
    g.drawString("Welcome to Java",10,35);

    in the body of HelloWorldCanvas’s paint() method. The result of these statements would appear as shown in Figure [fig-drawstr].

    Graphics Drawing Methods

    The Graphics class discussed in the previous section also has methods that can be used to draw geometric shapes in different colors. These methods can be used to create graphical user interfaces that are more interesting or to give a visual representation of data, such as a pie chart or a bar graph.

    There are two Graphics methods for drawing rectangles, fillRect() and drawRect() (Fig. 2.8). The first draws a rectangle and fills it with the current drawing color and the second just draws the outline of the rectangle. Using the Graphicsobject, g, each of these is called in the same way as the drawString() method from the previous example. Each of these methods takes four int arguments, which specify the rectangle’s location and size. Thus, a call to fillRect() would take the form

    g.fillRect(x,y,width,height);

    where x and y arguments specify the location of the upper left corner of the rectangle as being x pixels from the left edge of the window and y pixels down from the top edge of the window. The width and height arguments specify the width and height of the rectangle in pixels. The drawRect() method also takes the same four arguments.

    A Graphics object stores a single color for use in drawing shapes or displaying strings with drawString(). If we wish to draw an interesting scene in the JFrame, we need to understand how to use colors.

    For a given Graphics object, such as g, the setColor() method will set its color for all subsequent drawing commands. The setColor() method takes, as an argument, an object of type Color. All we need to know about the Color class is that it is contained in the java.awt package and that it contains 13 constant Color objects corresponding to 13 common colors. Table [table-colors] lists the 13 Color constants. Each name corresponds to the color it will represent in the program.

    Predefined color constants in the Color class.
    Color.black Color.green Color.red
    Color.blue Color.lightGreen Color.white
    Color.cyan Color.magenta Color.yellow
    Color.darkGray Color.orange
    Color.gray Color.pink

    To demonstrate how the new Graphics methods can be used for creating more interesting graphical programs, let’s develop a plan for displaying the two messages, “Hello, World!” and “Welcome to Java.”, on an JFrame, but this time we will draw the first inside a colored rectangle and the second inside a colored oval. For the rectangle, let’s use the drawRect() method to create its border. We can choose some arbitrary colors, say, cyan for filling the rectangle, blue for its border, and black for the string itself. In order to have the message visible we should fill a rectangle with the color cyan first, then draw the border of the rectangle in blue and, finally, display the message in black.

    Drawing and filling a Graphics oval is very similar to drawing and filling a rectangle. Notice in Figure 2.8 that the fillOval() and drawOval() methods take the same four arguments as the corresponding rectangle methods. An oval is inscribed within an enclosing rectangle. The x and y arguments give the coordinates of the enclosing rectangle’s top left point. And the width and height arguments give the enclosing rectangles dimensions.

    All that remains is to choose the location and dimensions of the rectangles. We could specify one rectangle as having its upper left corner 25 pixels to the right of the left edge of the JFrame and 25 pixels down from the top edge. A medium sized rectangle could have a width of 140 pixels and a height of 40 pixels. The statement

    g.fillRect(25, 25, 140, 40);

    will fill this rectangle with whatever color happens to be g’s current color. A location 25 pixels to the right of the left edge of the rectangle and 25 pixels down from the top edge of the rectangle would have coordinates and . Thus, the statement

    g.drawString("Hello, World!", 50, 50);

    will display “Hello, World!” inside the rectangle. We can use similar planning to locate the oval and its enclosed message.

    Thus, we now have sufficient information to finish the paint() method for accomplishing our plan. The completed program is displayed in Figure [fig-hw2appletclass]. Note how we repeatedly use the

    import java.awt.*;
    import javax.swing.JFrame;
    
    public class HelloWorldGraphic  extends Canvas 
    { 
        // called after setVisible(true)
        public void paint(Graphics g) { 
            g.setColor(Color.cyan);      // Set color
            g.fillRect(25, 25, 140, 40); // Fill rectangle
            g.setColor(Color.blue);      // Set color
            g.drawRect(25, 25, 140, 40); // Outline rectangle
            g.setColor(Color.black);     // Set color
            g.drawString("Hello, World!", 50, 50); // Display string
            g.setColor(Color.yellow);          
            g.fillOval(25, 75, 140, 40); // Fill oval
            g.setColor(Color.red);
            g.drawOval(25, 75, 140, 40); // Outline oval
            g.setColor(Color.black);
            g.drawString("Welcome to Java", 50, 100);
        }//paint()
    
       // the program
        public static void main(String[] args){
            HelloWorldCanvas c = new HelloWorldCanvas();
            JFrame f = new JFrame();
            f.add(c);
            f.setSize(150,50);
            f.setVisible(true);
        }
    } //HelloWorldGraphic

    g.setColor()

    method to change g’s current color before drawing each element of our picture.

    Figure [fig-drawrect] shows what this program looks like. To experiment with this Java Swing application, download its sourcecode from the book’s Web site and compile and run it on your computer. Additional drawing capabilities will be explored throughout the text in sections that can either be covered or skipped.


    This page titled 2.2: Drawing Shapes with the Graphics Object (Optional) is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Ralph Morelli & Ralph Wade via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.

    • Was this article helpful?