programming.java--Lab 2 Chapter 2 Applets Now that you are familiar with your Java programming environment, we can shift our attention to understanding and using the Java language to describe and solve problems. That, after all, is the real focus of this course. In this and all subsequent labs, the sample lablets are provided for you on these lab pages so that you can begin the exercises immediately without having to type any lengthy programs. The Chapter 2 lablet is a class that uses a few of Java's built-in libraries to do some graphic manipulation, somewhat like we did in Chapter 1. In this chapter, though, we'll use the lablet to investigate the basic structure and syntax of Java programs. Lab Objectives In this lab, you will: Run the Chapter 2 lablet, Borders, to familiarize yourself with its behavior Inspect the lablet's code, to gain some understanding about how a Java program is written. Experiment with some of the features of a program, by modifying the lablet and interpreting the results of your changes. Continue learning about programming by modifying and extending the lablet--on your own--to produce new and different behavior. Exercises As will be our custom from here on, we'll begin this lab by asking you to run the lablet, which (as should be obvious, we hope) you can do by clicking on the link in this sentence. Tip: The lablet's page will appear in a new window. You may as well keep both windows open while doing this lab, resizing and moving them as necessary. Play with the lablet until you see how it works. How many clicks does it take to get from the biggest border to the smallest? Answer: Watch the button carefully as you click. What notable behavior does it exhibit? Answer: Now take a look at the applet's code. You can do this by going back to the window containing the applet and clicking on the link "the source" in that page (or by clicking on the link in this sentence). Tip: You'll find it useful to keep the source window open, too, while doing this lab. While you're reading the applet code, don't pay too much attention to the actionPerformed() method. While it's the place where much of the interesting behavior of the applet comes from, we'll have to defer talking about event handling until later. Do, though, take a close look at the code in the paint() method--that's the heart of this lab. Recall [p. 20 ] that a class like Borders, is a description of the data and methods for manipulating the data that belong to every object of that class. What are the names of the data members (also known as instance variables) of the Borders class? Answer: In Java, every data item has a type. Data types can be primitive, like int (representing integers, like 3 or -256) or classes, like Button. What are the types of the Borders instance variables? Answer: If a variable is declared [p. 44 ] inside a method definition, that variable is local to the method and has no meaning outside of the method definition. [p. 54 ] Which of our methods contains six local variables? Answer: What are the names of the methods of the Borders class? Answer: You've seen [pp. 35-38 ] that a method is a named sequence of statements that are to be executed when the name is used--either by the program or the run-time system--to call the method into action. How many statements are used in the definition of the init() method? Answer: How does the compiler determine where a method definition begins and ends? Answer: A method may have zero or more arguments, [p. 36 ] indicating information that will be sent to the method when it is called. Among the methods in the Borders class, which take one or more arguments? Answer: One way of finding out how the features of a language like Java work is by experimentation, using the compiler as an assistant. To see the purpose and nature of an aspect of Java, you can change part of a program and recompile it. If the compiler gives you an error message, the message can (sometimes) give you a useful clue about the rules of the language. If the compiler accepts your changes as legal, you can often get a further clue by then watching the program run and noting any changes in its behavior. Tip: It's a good idea to save a backup copy of the source code so you'll always have a clean original to which to return, in case you derange it beyond all recognition during your experiments. If you don't know how to save a copy of the source code, ask your instructor. What is the purpose of inheritance? The Borders class inherits [pp. 21-22 ] the methods and data of the Applet class, defined in the library package "java.applet." To turn off this inheritance, remove the code extends Applet and recompile your program. Tip: An easy (and easily undoable) way of removing a chunk of code is to "comment it out." Put a /* in front of extends Applet and then put a */ immediately after Applet--presto! you've just told the compiler to ignore everything between the comment delimiters. What error message does the compiler give you, and why? Answer: Undo the change you just made and then remove the line import java.applet.*; You've just made the definitions and declarations of the Applet class unavailable to the compiler. What happens? Answer: Undo the changes you just made. You'll do this after each modification, from here on. What does the init() method of an applet do? Remove or comment out the method definition from your applet (everything from public void init() to the closing "}" brace five lines later) and try to compile and run it. Does your changed version of "Borders.java" compile? Answer: If so, how has its behavior changed? Answer: Do we really have to declare each of our variables before we use them? Remove or comment out the code private Button resizeBttn; What error message does the compiler give you, and where? Answer: The appearance of our applet is determined by the library classes used in the paint() method. This method uses the classes Graphics [p. 42-43 ] for its drawing routines, Color, [p. 45 ] to set the drawing colors, and Dimension, [p. 48 ] to get access to the applet's size. When paint() is called, either by the runtime system or by your program calling repaint(), it is passed a Graphics object, belonging to the applet itself. This Graphics object, represented by g in the method argument, "knows" how to draw on the screen, so, for instance, when we make the statement g.fillRect(x, y, w, h); we are calling [p. 36 ] the Graphics method fillRect() belonging to the object g. What happens when you change the line in the paint() method that reads g.fillRect(x, y, w, h); to read fillRect(x, y, w, h); Answer: The fillRect() method requires four int arguments, representing the x and y coordinates of the upper-left corner of the rectangle, and the width and height of the rectangle. [p. 40 ] We set these in the first lines of the paint() method, like this:
Dimension appletSize = getSize();
int x = 0,
y = 30,
w = appletSize.width - x,
h = appletSize.height - y;
What happens when you change the line y = 30, to read y = 50, Answer: Order is vitally important in method arguments. What happens when you change the line fillRect(x, y, w, h); to read fillRect(y, x, w, h); Answer: In Java, as in most programming languages, statements are executed in the order in which they are written. To see why this is important, swap the statements g.setColor(Color.black);
g.drawRect(x + inset, ...);
g.setColor(Color.white);
g.fillRect(x + inset + 1, ...);
So that they appear in this order g.setColor(Color.white);
g.fillRect(x + inset + 1, ...);
g.setColor(Color.black);
g.drawRect(x + inset, ...);
Hint: You can save a lot of typing here by creative use of Cut and Paste. Explain what happens and why. Answer: As you've probably guessed by reading the lablet code, the Color class is used to represent and manipulate colors. Besides the thirteen predefined color constants, [p. 45 ] you can define colors of your own, by specifying the amounts of red, green, and blue. Notice that four times in paint() we call the Graphics method setColor() to set the current drawing color. Change any or all of these to paint the border in any color you wish. Before we make the last setColor() call we make a new color of our own by declaring a new local variable: Color fillColor = new Color(255, 200, 200);
g.setColor(fillColor);
The color specified by (255, 200, 200), as you've seen, is a light pink. Change it to (200, 20, 100)--what color results? Answer: Change the lablet so that the background color is a deep blue-violet, like this, rather than red. For the purposes of drawing, coordinates are measured in pixels [p. 36, footnote ] from the top left of the component (the applet, in this case). The inset instance variable is used to measure the amount the border is inset from the top left of the background border, like this: Change the lablet so that the x-inset (horizontal) is twice as large as the y-inset. To do this, you'll have to change the width argument to the drawRect() and fillRect() calls. We've just scratched the surface of all the Graphics methods available to us. For example, we can also draw ovals. Try it, replacing every fillRect() call by a call to fillOval(), using the same arguments as in the original, and replacing the call to drawRect() by a call to drawOval(), again using the same arguments as in the original. Before you run the program, try to predict exactly what the result will be. While the text includes descriptions of some of the most important Java classes and their methods, space considerations dictated that we leave a lot out. One of the helpful things the people at Sun Microsystems did was to provide complete online documentation of all the Java classes. Spend some time looking at the documentation--it's located at http://www.javasoft.com/products/jdk/1.1/docs/api/packages.html If you're using your own computer, go to this page and bookmark it--you'll spend a lot of time in the future looking at it. Postlab Exercises Write an applet that draws a digital clock or watch on the screen and displays the current time on its face. We're not asking you to write the program so that the time is continually updated (that will come later, in Chapter 11). For now, just display the time when the applet was started. You can use the Date class to retrieve the current time, as follows: Date myTime = new Date();
int myHour = myTime.getHours();
int myMinute = myTime.getMinutes();
int mySecond = myTime.getSeconds();
Since your applet won't do any event handling, you won't need an actionPerformed() method and so you should also remove the phrase implements ActionListener from the class header. In fact, since you won't have a button to add to the applet, you won't even need an init() method--the only method your applet will need will be paint(). Look at the sample applet on pp. 42-43 for an idea of what you'll write. Write an applet that displays a page from an appointment book for the current date. We leave it to you to design the page any way you like. Check out the documentation describing the Graphics class, and you'll see that it provides methods for drawing a number of common shapes. Last updated: December 4, 1998 Rick Decker Department of Computer Science Hamilton College Clinton, NY 13323