Lab 4 In-Class: Applets, Graphics and GUI containers

Lab Objectives

  • Learn about constructors with the Color class
  • Gain more experience with graphics using applets.
  • Learn the basics of using frames and panels and textboxes.

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.

Applets, 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 and then represent the color of each pixel by a numeric code (this idea is discussed in section 2.7 of the text). In most computer languages, including Java, the color is specified by 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 Color.red, 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:
       page.setColor(myColor);
will set the current drawing color to be myColor . The file Colors.java contains an applet 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 Colors.java to your lab4 directory, open it in the Eclipse editor, and execute the program (Run As... Java Applet).

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 98 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 applet to make sure it is correct.

  6. Now add a rectangle in the center of the applet. The height of the rectangle should be half the height of the applet 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 applet to make sure it is correct before proceding.

  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
            00000000000000001111111100000000
    
    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 applet. Is your rectangle green?

  8. Now add the following statements to the program: Run the program -- restart the program several times (do this by clicking on the Applet menu on your applet window and selecting the restart option) 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 98. The descriptions are on pages 97-99. Pay particular attention to how an arc is defined (note the diagram on page 99).

Now save files MoreShapes.java to your lab4 directory. Look at the file, then execute it. (Note: Sometimes the background color doesn't initially show up - use the Applet | Restart option on the menu to get the color.) To be sure you understand the arc methods open MoreShapes.java in the editor and do the following:


Creating a Pie Chart Write an applet 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 applet rather than an application 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.JApplet which is the superclass for applets.

  3. Do NOT check the box for the main method stub (remember an applet has a print method rather than a main method).

  4. Click Finish. You will notice in the program that javax.swing.JApplet 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 MoreShapes.java 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 resize statement, then paste the code into PieChart.java. You can go ahead and add the ending brace for the method so you have the complete stub. Note that Eclipse has automatically added the import java.awt.Graphics statement.

  6. Add a sentence in the header documentation to explain what the program does; change the documentation before paint to indicate what the paint does (you can say the same thing as in the header doc!).

  7. 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%
    Transportation15%
    Food15%
    Educational25%
    Miscellaneous10%

    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).

  8. Print the completed program.


Frames, Panels and Labels for GUI Applications

In this activity, you will start to learn how to create applications that have Graphical User Interfaces (GUIs). This program also serves as a nice example of how multiple objects can work together to create a desired effect. Specifically, you are going to work with 3 new classes: JFrame, JPanel and JLabel.

A Frame is a object that is used to represent a window for a Java application. A Panel provides a way to group components together and is used to organize the layout of the GUI. A Label is a GUI component that is used to present some text or image within the GUI. The file FirstGUI.java contains a sample program that puts together these objects. (A similar example is on page 143 of the textbook.) Download FirstGui.java to your lab4 directory and open it in the Eclipse Editor. Run the program, leaving the small GUI window up so you can compare what it looks like to the code in the program.

Observe the following:

Now experiment with some of the parameters as follows:

Multiple Panels

Windows often contain multiple panels to create separate groups of GUI components. The code listing on pages 145-146 of your textbook shows an example of "nested" panels. Observe that this program creates two unique subpanels. These subpanels are added to a third (primary) panel which is ultimately added to the frame.

Working from this example, create a new program called Stoplight.java that has three separate subpanels. Note that when you create a new class in Eclipse for this you do want the main method stub! Your GUI should have the following features:

  1. The first panel should have a red background and contain the text "Stop". The second should have a yellow background and contain the text "Yield". The third should have a green background and contain the text "Go".

  2. All three subpanels should be sized to 150, 150.

  3. All three subpanels should be contained in a blue "mainPanel".

  4. If you follow the example in the book, your subpanels will come out horizontally. Modify your code to force the panels to line up vertically. (Hint think about the size of the mainPanel).

  5. Print your completed program.

Image Labels

JLabels are mostly used to display text on the GUI. However, JLabels can also be used to display images. To do this, you first need an ImageIcon object. Assuming that you have a file named picture.gif in your project directory, you can invoke the ImageIcon constructor:

         ImageIcon icon = new ImageIcon("picture.gif");
Once you have an ImageIcon object, you can simply pass it to the constructor for the JLabel:
        JLabel label1 = new JLabel(icon);
An example program using images is on pages 147 - 148 of the text that creates a more complicated label - one with some text, the icon, and positioning information. The one-parameter constructor used above creates a label consisting of just the icon.

The final program for today is to create an interface that uses multiple panels to separate a collection of dog images and from a set of cat images.

  1. Create a new class called CatsNDogs.

  2. Create a frame that has a main panel with two subpanels.

  3. Create a label for each of the subpanels ("Cats", "Dogs")

  4. Save the archive file pics.tgz to your Labs directory.

  5. Change directories to Labs and uncompress the archive using the command
         tar xzf pics.tgz   

  6. Verify that there is a pics directory in Labs that contains four .gif files.

  7. Create the appropriate ImageIcons to read in the 4 pictures. Note: Eclipse is looking for the files in the project directory (Labs), but the files are in Labs/pics. When you specify the filename to the ImageIcon constructor, you will need to specify the appropriate relative path name.

  8. Create JLabels for each of the pictures and add them to the appropriate panel.

  9. Adjust sizes of your panels if necessary so all four pictures appear.

  10. Print your final program.

What to turn in