Lab 4 In-Class: HTML, Applets, and Graphics

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, 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 statement page.setColor(myColor) then will set the foreground color for the page to be the color defined by the myColor object.

The file 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 the program and its associated HTML file Colors.html to your lab4 directory (for the HTML file right click on this link to save). Compile the program then run it using the appletviewer (remember the command is appletviewer Colors.html).

Open in emacs and 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. Compile and run the applet to make sure it is right.
  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. Compile and run the program 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
    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. Compile and run the program. Is your rectangle green?
  8. Now add the following statements to the program: Compile and run the program -- restart the program several times (do this by clicking on the Applet menu on your applet window) 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. Compile and 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.

Introduction to HTML

HTML is the HyperText Markup Language. It is used to describe how text, images, and multimedia are displayed by Web browsers. In the last lab you used an HTML file to display your applets. In this lab you will learn more about HTML so that you can create a web page containing headings, interesting fonts, lists, and links as well as applets. This handout provides an introduction to HTML.

HTML uses tags to describe the layout of a document; the browser then uses these tags to figure out how to display the document. Tags are enclosed in angle brackets and are not case sensitive. For example, <title> is a tag that indicates that this section contains the title of the document, and could also be written <TITLE> or <Title>. Many tags, including <title>, have corresponding end tags that indicate where the section ends. The end tags look just like the start tags except that they start with the character /, e.g., </title>. So the following text means that the title of the document is CPSC 120 Lab 4:

<title>CPSC 120 Lab 4</title>
There are a few tags that almost every document will have: <html>, <head>, <title>, and <body>. Here is an example of a simple HTML document:
    <title>CPSC 120 Lab 4</title>

  In this lab you will learn about HTML, which is lots of fun
  to use.  In particular, you will learn how to use fonts,
  paragraphs, lists, links and applets in a web page.  Now you
  can make your own web page for your friends to visit!
Click here to see what this looks like in Firefox. Change the size of the Firefox window (click and drag any corner) and see how the text is reformatted as the window changes. Note that the title appears on the title bar of the window, not as part of the document.

The head of a document (everything between <head> and </head>) contains the introduction to the document. The title goes in the head, but for now we won't use the head for anything else. The body of a document (everything between <body> and </body>) contains everything that will be displayed as part of the document. Both the head and the body are enclosed by the HTML tags, which begin and end the document.

This document contains only plain text, but an HTML document can have much more structure: headings, paragraphs, lists, bold and italic text, images, links, tables, and so on. Here is a document containing a heading, two paragraphs, and some fancy fonts:

    <title>CPSC 120 Lab 4</title>

  <body bgcolor="lightgreen">
  <h1 align="center">Lab 4 In-Class</h1>

  There's lots you can do with HTML.  You can make the page a pretty
  color, <u>underline</u> text,
  or put it in <i>italics</i> or <b>bold</b>.  You can also 
  make lists, links, and tables, but we'll get to those later.

  <p>When you go on to a new topic, you can start a new paragraph.  
  You don't
  have to worry about indenting or otherwise formatting the paragraph -- the
  browser will decide that for you.  Usually it leaves a blank line.
  If you just want to go to a new line, without
  any vertical space, you <br> can <br>do <br> that <br> too. 
Click here to see what this looks like in the browser.

In this document the <h1> tag creates a level 1 heading. This is the biggest heading; it might be used at the beginning of the document or the start of a new chapter. Level 2 through level 6 headings are also available with the <h2> through <h6> tags.

The <p> tag creates a new paragraph. Most browsers leave a blank line between paragraphs. The <br> tag just goes to the next line, without leaving a blank line. The <b> tag creates bold text, the <i> tag creates italic text, and the <u> tag creates underlined text. Note that each of these tags is closed with the corresponding end tag. The bgcolor attribute on the body tag sets the background color.

Note that line breaks and blank lines in the HTML document do not matter -- the browser will format paragraphs to fit the window. If it weren't for the <P> tag, the blank line between the paragraphs in this document would not show up in the displayed document.

Exercise #1: For a file to be visible on the Web, it must be where the web server knows how to find it. The web server that runs on is set up to look in the public_html directory under each user's home directory on the Linux server, so you need to create this directory as follows: Now if you save a .html file in your public_html directory, you can view it from a web browser anywhere. If your user name is astudent and the file name is Test.html, the URL for your page is
Now on to the exercise!

In Emacs, open a new file called MyPage.html in your public_html directory. Write a simple web page about things that interest you. Your page should contain at least the following:

Please Note! We understand how excited you are to be creating a web page. While we encourage you to embellish this document with your personal expression and creativity, for now we are more interested in learning the mechanics of HTML. We recommend that you use the lab time wisely and keep your page simple for now. You can always make changes to this page later in the semester.

When you are done, view your document from Firefox. Just type in the URL, don't use File | Open Page.



Lists We often want to add a list to a document. HTML provides two kinds of lists, ordered (e.g., 1, 2, 3) and unordered (e.g., bulleted). A list is introduced with the <ol> or <ul> tag, depending on whether it is ordered or unordered. Each list item is introduced with a <LI> tag and ended with the </LI> tag. The entire list is then ended with </ol> or </ul>, as appropriate. The following is an ordered list of instructions for creating a list:

      <li>Type the tag <ol> (if you want an ordered list) or
           <ul> (if you want an unordered list)
      <li>For each item in your list, type the <li> tag followed
           by the text you want in the list.
      <li>To end the list type the tag </ol> or </ul> 
           (depending on the list type - match the beginning tag)
Click here to see what this looks like in the browser.

Exercise #2: Add a list, either ordered or unordered, of at least three elements to your document.

Links Links connect one document to another. Links are created in HTML with the <a> tag. When creating a link you have to specify two things:

For example, the code below creates the link shown, which goes to the CPSC 120 home page:
Visit <a HREF="">my favorite course!</a>

Visit my favorite course!

Exercise #3: Add at least one link that ties in to the material on your page. Don't link to the course home page!

Tables Tables let you align elements in rows and columns; they can be used in the traditional way to display data, or simply to format page elements. There are three important tags for an HTML table:

For example, the code below creates the table shown:
<table border=1>
<td>Test 1</td>
<td>Test 2</td>

<td>Mickey Mouse</td>

<td>Donald Duck</td>

Name Test 1 Test 2
Mickey Mouse 78 92
Donald Duck 83 87

A few things to note:

Exercise #4: Use a table to add your class schedule to your page. Label the columns with days of the week (M-F), and the rows with "morning" and "afternoon." (Since MWF and TTh classes meet at different times, it's more complicated if you try to use actual times.) In each cell put the classes you have on that day and time, one per line. You can use an unordered list or the <br> tag to get them on separate lines.

Images You can add any picture to a web page with an <img> tag. The tag must specify the source file using the SRC attribute. For example,

       <img SRC="smiley.gif">
adds the picture in the smiley.gif file (note - this assumes that file is stored in the same directory as the web page). You can scan pictures, use pictures taken from a digital camera, or get copies of pictures that are on the web (as long a they are not copyrighted!). The image files should be either .jpg or .gif since most browsers know how to display these formats (in other words they know the compression algorithms that can decode the image).

Placement of images can be tricky - they often don't show up where you want. Using a table to help place them is a common trick. You'll do this in post lab!

More Applets and 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 and MoreShapes.html to your lab4 directory. Look at the .java file, then compile it and view it using the appletviewer (the command is appletviewer MoreShapes.html). (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 in emacs and do the following:

Exercise #5: Write an applet that draws a pie chart showing the percentage of household income spent on various expenses. To do this either copy to and then edit it (you'll have to delete a lot) or open a new file. Similarly copy MoreShapes.html to PieChart.html and edit it.

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

Exercise #6: Now add your applet to the web page you created earlier in the lab. You will do this using the <APPLET> tag that is in the .html file you are using with the applet viewer -- you can just copy it out of that file and paste it into your other file (choose a size for the applet that makes sense). The applet will appear wherever you insert the applet tag. Note that you will have to copy the PieChart.class file to your public_html directory for the web server to find it. Of course, the web page that you created earlier should already be in that directory.

What to turn in

You don't need to e-mail the .html file in your public_html directory -- we can load it from there (if you have everything in the correct place with the correct name!).