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:
- 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.
- 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.
- 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.
- 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).
- Run the applet to make sure it is correct.
- 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.
- 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?
- Now add the following statements to the program:
- Declare colorCode to be a variable of type int;
- Declare a constant COLOR_MAX and initialize it to 16777216.
Put your declaration up with the other constants near the
beginning of the main method.
(NOTE: This number comes from
the fact that a color is represented by a 24 bit code - how
many unique items can be represented by a 24 bit code?)
- Note that the Random class has already been imported into
the program and generator has been instantiated as a Random
object. Use generator and the nextInt method
to generate a random integer value
in the range 0 - 16777215 (use the constant just declared!).
- replace the number 65280 in the Color constructor above with the
variable colorCode
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.
- 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.
- 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:
- [READ ALL OF THIS BEFORE DOING ANYTHING!!]
Before you set the color for the strings,
instantiate a new Color object that is sort of "half way" around
the color spectrum from the color of the rectangle. We'll do
this by adding
128 (half of 256) to the red, green, blue attributes of the rectangle color.
However we can't just add 128 because the Color constructor that has 3 integer
arguments requires that the integers be in the
range 0 - 255. To get the codes back in the proper range we
take the remainder when dividing by 256.
Hence, what you need to do for each color attribute, add 128 then
take the remainder when the result is divided by 256. For example,
if redCode is currently 220 then when you add 128 you get 348
then taking the remainder when you divide by 256 gives 92. You can
either introduce new variables for each of the new codes and
store the new values in those variables before instantiating the
new Color object OR you can just put the calculations for the new
codes directly in the arguments for the constructor.
- Set the color for drawing to be your new color instead of black
(or whatever color you used before).
- Test your program!
- 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:
- Observe that currently the red arc has a start angle of 0
and an arc angle of 90. This draws a quarter of an oval.
Change the start angle to 45 and run
to see what happens. Where does the arc start? How far does it go?
- Change the arc angle to 180 and see what happens.
- Currently the black outline arc has a start angle of 120
and an arc angle of 160. Observe what this looks like then change
the arc angle to 300. See what this does.
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:
- Choose File, New, Class to create a new class and type PieChart in the
Name box (so far the usual steps!).
- 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.
- Do NOT check the box for the main method stub (remember an applet
has a print method rather than a main method).
- 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.
- 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.
- 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!).
- 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 Utilities | 35%
|
Transportation | 15%
|
Food | 15%
|
Educational | 25%
|
Miscellaneous | 10%
|
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).
- 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:
- When the frame is instantiated, it passes a string
to the consructor. How is that string used?
- After it is created, the frame object calls a method,
setDefaultCloseOperation This method is setting a
value for one of the frame's attributes. You will frequently see
methods that begin with the word "set".
- After it is created, the Panel object also "sets" values for
some of its attributes.
- The labels are first instantiated, then
placed on the panel by invoking the "add" method of
the panel class. Do you think that the order matters?
- The last thing that happens is that frame invokes a method to make
itself visible - This displays the frame to the screen.
Now experiment with some of the parameters as follows:
- Change the preferred size to something very small - say 40, 30. Run to see
what happens.
- Now try very large - at least 400, 300. What happens to the labels?
- Change the order in which the labels are added (just change the
statements that add, not the instantiation statements). What happens?
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:
- 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".
- All three subpanels should be sized to 150, 150.
- All three subpanels should be contained in a blue "mainPanel".
- 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).
- 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.
- Create a new class called CatsNDogs.
- Create a frame that has a main panel with two subpanels.
- Create a label for each of the subpanels ("Cats", "Dogs")
- Save the archive file pics.tgz to your Labs
directory.
- Change directories to Labs and uncompress the archive using the
command
tar xzf pics.tgz
- Verify that there is a pics directory in Labs that
contains four .gif files.
- 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.
- Create JLabels for each of the pictures and add them to the
appropriate panel.
- Adjust sizes of your panels if necessary so all four pictures
appear.
- Print your final program.
What to turn in
- Turn in hardcopy of your four files: Colors.java
PieChart.java, StopLight.java and CatsNDogs.java
- Tar up your lab4 directory (change to your lab4 directory,
then do
tar czf lab4.tgz .
)
and send the tar file to your instructor. Be sure the subject line
says cpsc120 lab4.