Lab 4 In-Class: Graphics

Lab Objectives

  • Learn about constructors with the Color class
  • Gain more experience with graphics.

Getting Started

Log onto the Linux system, open Firefox and an xterm window. In Firefox, go to the home page for this class and open up this lab. In an xterm, go to your Labs directory for this course and create a lab4 subdirectory for today's work. Change into that subdirectory.

Graphics, and Color Codes

The basic scheme for representing a picture in a computer is to break the picture down into small elements called pixels, short for picture elements, and then represent the color of each pixel by a numeric code (this idea is discussed on pages 803 and 804 of the text). There are many systems for representing colors. One of the most common systems on computers is to use the same three additive colors that computer displays use. In this system the three additive colors are represented with three numbers -- one representing the amount of red in the color, another the amount of green, and the third the amount of blue. These numbers are referred to as the RGB value of the color. In Java, each of the three primary colors is represented by an 8-bit code. Hence, the possible base 10 values for each have a range of 0-255. Zero means none of that color while 255 means the maximum amount of the color. Pure red is represented by 255 for red, 0 for green, and 0 for blue, while magenta is a mix of red and blue (255 for red, 0 for green, and 255 for blue). In Java you can create your own colors. So far in the graphics programs we have written we have used the pre-defined colors, such as, from the Color class. However, we may also create our own Color object by specifying the red, green, and blue attributes. One way to create a Color object is to declare a variable of type Color and instantiate it using the constructor that requires three integer parameters -- the first representing the red attribute (the amount of red), the second the green attribute, and the third the blue attribute of the color. The signature for that constructor is
       Color (int r, int g, int b)
where r is the integer code for red, g the code for green, and b the code for blue. For example, the following declares the Color object myColor and instantiates it to a color with code 255 for red, 0 for green, and 255 for blue.

       Color myColor = new Color(255, 0, 255);

The Graphics object (page) can use a color object to set the foreground color for the page. The statement:
will set the current drawing color to be myColor . The file contains an application that defines myColor to be a Color object with color code (200, 100, 255) - a shade of purple - and later redefines myColor to be a Color object with code (100, 100, 200).

Save to your lab4 directory, open it in the Eclipse editor, and run the program.

Now do the following:

  1. Study the code to see what is going on. Note the two places where the Color constructor is invoked to instantiate a new Color object. Also note how the x, y, width, and height variables are computed to place the two ovals (they are computed in terms of the PAGE_WIDTH and PAGE_HEIGHT constants). Finally note the use of the drawString method. The signature for the method is given on page 806 of the text.

  2. Change the first instantiation of a Color object so the color code is (0,0,0) --- absence of color. What color should this be? Run the program to check.

  3. Try a few other combinations of color codes to see what you get. Find something you like for each of the ovals that are drawn.

  4. Use the drawString method to put your name centered in the bottom right oval. Place your statement in the code where indicated by the comment (after the oval is drawn). Be sure to use the current values of x, y, width, and height in calculating the x and y values that position the string (you will need to make an adjustment that depends on the length of your name similar to the 35 used in positioning the "Color Codes" string).

  5. Run the application to make sure it is correct.

  6. Now add a rectangle in the center of the frame. The height of the rectangle should be half the height of the frame page and the width should be half the width of the page. Use the x, y, width, and height variables to calculate the position. The calculations should involve the PAGE_WIDTH and PAGE_HEIGHT constants. Run the application to make sure it is correct before proceeding.

  7. Now we will modify the program to generate random colors using a different constructor. (NOTE: a class can have multiple constructors - having more than one version of a method, including a constructor, is called method overloading.) There is a constructor for the Color class that takes a single integer as an argument. Its signature is:
             Color (int rgb)
    The first 8 bits of the integer argument are ignored while the last 24 bits define the color -- 8 bits for red, 8 for green, and the last 8 bits for blue. Hence, the bit pattern
    should represent pure green. Its base 10 value is 65280. Just before your code for the rectangle (but after the comment about drawing a rectangle) add a new instantiation of the myColor object to
            myColor = new Color (65280);
    You also need to use the setColor method to set the color to myColor. Run the application. Is your rectangle green?

  8. Now add the following statements to the program: Run the program -- restart the program several times so you can see the different random colors generated.

  9. The Color class has methods that return the individual color codes (for red, green, and blue) for a Color object. The signature for getRed is as follows:
            int getRed()
    returns the code for the red component of the myColor object (redCode should be a variable of type int). The methods that return the green and blue components are getGreen and getBlue, respectively. Add statements to the program, similar to the above, to get the three color codes (you need to declare some integer variables to store the codes). Then add statements such as
            page.drawString("Red: " + redCode, ____ , ____ );
    to label the rectangle with the three color codes (this assumes your variable for the red attribute is redCode). You need to fill in the blanks with appropriate coordinates so each string is drawn inside the rectangle -- to do this make adjustments to the x and y coordinates for the rectangle. You also need to set the drawing color to something such as black so the strings will show up. Run the program to make sure it works. Restart several times to see the different colors and their corresponding codes displayed.

  10. If you restarted the program enough times you probably noticed that the black (or whatever color you used) strings didn't always show up. Our final task is to fix this so the color of the strings will always show up. We'll do this by creating a new color from the red, green, blue attributes of the rectangle color. So add the following to your program to get the new color:

  11. Test your program!
  12. Print your final program.

More Graphics

So far we have drawn rectangles, ovals,and strings but there's lots more that can be done with Java graphics. For starters, you can draw lines and arcs. All of these shapes can be drawn in outline with the "draw" methods (drawRect, drawArc, etc), or drawn in filled in form with the "fill" methods (fillRect, fillArc, etc).

Refer to the list of graphics method on page 806. The descriptions are on pages 805-808. Pay particular attention to how an arc is defined (note the diagram on page 807).

Now save files to your lab4 directory. Look at the file, then execute it. To be sure you understand the arc methods open in the editor and do the following:

Creating a Pie Chart Write an application that draws a pie chart showing the percentage of household income spent on various expenses. To do this we create a new class in Eclipse but since this is an application that uses graphics we need to do a couple of things in a different way as follows:

  1. Choose File, New, Class to create a new class and type PieChart in the Name box (so far the usual steps!).

  2. Note the Superclass box contains java.lang.Object, which is the superclass for applications. Change that to javax.swing.JFrame, which is the superclass for frames, which are a type of window.

  3. Check the box for the main method stub.

  4. Click Finish. You will notice in the program that javax.swing.JFrame was automatically imported. Unfortunately Eclipse did not automatically put the paint method stub for you.

  5. Probably the easiest way to add the stub for the paint method is to copy from the program (of coure you could just type it in). To copy go to the MoreShapes program and copy the code from the comments above paint through the clearRect statement, then paste the code into You can go ahead and add the ending brace for the method so you have the complete stub, and remove the variable declarations. Note that Eclipse has automatically added the import java.awt.Graphics statement.

  6. The main method can also be filled by copying the code of the main method from the file. You should note, however, that the main method of creates an object of type MoreShapes. The main method of should create an object of type PieChart.

  7. Add a sentence in the header documentation to explain what the program does. Also, change the documentation before paint to indicate what the paint method does (you can say the same thing as in the header doc!) and change the documentation for the main method (you can copy the documentation for the main method from

  8. Now you are ready to add the code to create the pie chart. Think about what shapes make up a pie chart to plan the program. For your pie chart use the percentages below:
    Rent and Utilities35%

    Each section of the pie should be in a different color, of course. Label each section of the pie with the category it represents -- the labels should appear outside the pie itself. Be sure your pie pieces are the appropriate proportion of a circle (for example, the one for educational expenses should be 25% of a circle).

  9. Print the completed program.

What to turn in