Computer Science 120
Introduction to Programming

Spring 2011, Siena College

Lab 0: An Introduction to Java and Objectdraw
Due: the start of your next lab session

This first lab introduces you to the tools that you will use this semester. Your task is to construct a Java program that draws an image resembling a roadside warning sign, but with a message more appropriate for a computer screen:

First you will need to determine the Java commands required to draw such a picture. Then you will write a Java program that draws and modifies the picture in simple ways in response to actions the user performs with the mouse.

Given space limitations, you will work in pairs on this lab.

Objectdraw Primitives

To help you learn how to create graphical objects, we have constructed a simple tool in which you can experiment interactively with the graphics primitives. This tool lets you create and modify objects by clicking buttons and filling in fields that describe the locations and dimensions of the objects. If you think of this program as a drawing program (like Adobe Photoshop) you will quickly conclude it is the worst drawing program in the world. Its interface is designed specifically to use mechanisms similar to those you will use from within your programs, and certainly not for usability as a drawing program. Hence its name: NotPhotoShop.

This part of the lab involves two steps: (i) completing a tutorial on NotPhotoShop, and (ii) using it to draw your own rendition of our "no clicking" sign.

Getting Started

The lab computers are not part of the college network, but are managed by the School of Science. Your login (username) should be the same as your Siena login (i.e., the part of your email address before @siena.edu), but your password is different. This login and password will work in any of the public labs in Roger Bacon. If you have not previously changed your default password to one of your own choosing, please do so now.

The files you create in your "network drive" in this account are not stored on the computer on which you are working. Instead, they will be stored on the School of Science file server. You can access these same files on any computer in our lab or elsewhere in Roger Bacon.

Navigate to your network drive. A folder hierarchy has been created for you inside a folder named csis120. You should have a folder named common, which will take you to the common course folder, and a folder named hw, which you will use to submit your work when you are done.

Before you can get started, you will need to copy the lab starter files into your own account. Follow this link to retrieve a "zip file" of today's starter code. It should open up a program called WinZip. If you are asked, click "Use Evaluation Version". This will bring up a window showing the contents of the starter file. Click the "Extract" button at the top. In the file selector, find your csis120 folder and select that, then click "Extract".

You should now have a file called NotPhotoShop and a folder called NoClicking in your csis120 folder. The first one you will use is NotPhotoShop. To run NotPhotoShop, double-click on the NotPhotoShop icon. Our drawing program will display a large window on your screen that should look like this:

The components in this window are divided into five main units.

The Drawing Window: The large rectangle appearing on the upper portion of the right side of the window is the area in which the drawing you create will appear. We will often refer to this area as the "canvas."
The Mouse Tracker: As you move the mouse about in the drawing window, the coordinates of the mouse's position within the window will be displayed next to the labels "x" and "y" that appear immediately below the drawing window. Try it! You will often need the coordinates of screen locations to control the placement of the objects you want to create.
The Object Constructor: The shaded area just below the mouse tracker contains the mechanisms you will need to describe and create the components of a drawing. The layout of the items in this region is designed so that the form of the information you input to create an object within this program will resemble the text you would have to enter to create a similar object if you were actually writing a Java program.
The Method Invocation Buttons: There are a number of methods you can apply to modify or obtain information about any of the graphical objects you create in a program. The collection of buttons below the constructor can be used to apply such methods to any of the objects currently present in the drawing window.
The Output Area: Of course, things can go wrong. If you specify some improper information when trying to create or modify an object, the system will display a brief message in the output area that appears along the left margin of the program's window. This area is also used to display descriptions of object properties requested by pressing certain method invocation buttons.

Creating Graphical Objects

To see how all these components work, let's add an object to the display.

You can begin by specifying the object type. The type of object to be created is controlled by the pop-up menu located just to the right of the word "new" in the constructor area. By default, the program starts with the FramedRect item selected in the menu. If you depress the mouse on the box labeled FramedRect, a list of the other choices will appear. Six options are available: FramedRect, FilledRect, FramedOval, FilledOval, Line, and Text.

Select Line instead of FramedRect. As you do this, notice that the labels on the text entry boxes to the right of the menu change to reflect the kinds of information you need to enter to specify the appearance of a line rather than a rectangle. For a framed rectangle, you need to enter the coordinates of its upper left corner and its width and height. For a line, you need to enter the coordinates of the two endpoints. Use the menu to select other options to see what information they require. To display a piece of text you enter the text to be displayed (although the box for entering the text is rather small) and the coordinates of the upper left corner of the rectangle in which the text should be placed. Ovals require the same input as rectangles; the values that you enter for an oval define rectangular bounds within which the oval is drawn.

To continue, make sure that FramedRect is the selected menu item. Fill in the boxes to the right of the menu with values to create a 100x100 rectangle at a location 70 pixels from the top of the drawing area and roughly centered between the left and right boundaries of the drawing area. To determine the actual x value to enter for this rectangle, position the mouse cursor where you estimate the left edge of the rectangle should be and use the "mouse meter" to determine the x coordinate of that point. Enter this value in the box labeled x immediately to the right of the menu. Then enter 70 as the y coordinate and 100 for both the width and height.

Once all these values have been entered, press the Construct button and the rectangle will appear.

Changing Object Attributes

When your rectangle appears, it is "decorated" with small black boxes on the edges and corner, indicating that it is the "selected" graphical object. By default, the most recently constructed object will be selected. When multiple objects are displayed, you can change the selected object by clicking within the object you wish to select.

The buttons below the object construction controls can be used to modify the currently selected object. For example, if your rectangle isn't positioned quite where you wanted it, you can move it around using the move(...) and moveTo(...) buttons. To try this out:

If you enter any invalid information, a brief message will be displayed in the output area, and the dialog box will remain on the screen so that you can correct the error. Common errors include entering non-numeric characters in numeric fields or leaving fields blank.

As with object construction, the text shown in the move(...) dialog box is designed to resemble the text you would include in a program if you wanted to instruct the computer to move an object.

If you press moveTo(...), you will be asked to specify new coordinates for the origin of the selected object. In the case of a rectangle, the rectangle will be moved so that its upper left corner is placed at the specified point. The setWidth(...) and setHeight(...) buttons invoke methods that let you change the dimensions of an object. They display a dialog box in which you must enter the new value to be used for the dimension being changed. It is not possible to set the width or height of a Line. If you try to use setWidth or setHeight while a Line is the selected object, the program will simply display a complaint in the output area.

There is one other button that allows you to change the appearance of an object after it is created. If you find your black rectangle boring, you can easily change its color by pressing the setColor(...) button. To do this:

The dialog that appears when you use the setColor(...) button does not attempt to present a display that mimics what you would use to change the color of an object from within a Java program. The conversion, however, is simple. The items within the dialog box are each a color name preceded by the word Color. If "selected" is the name of an object whose color you want to change to yellow, then within your program you would just type

selected.setColor(Color.yellow);

Later in the semester, you will learn how to select colors other than the small set with which names are associated.

Determining Object Attributes

After you have moved an object up and down a few times to get it right where you want it, you may not actually know where it is. That is, you may not know the exact coordinates of its upper left hand corner or remember its dimensions. Luckily the computer knows and will tell you if you press the correct buttons. The getLocation() button near the right end of the top row of buttons will display the x and y coordinates of the upper left corner of any object (except a Line). Try it. The coordinates will be displayed in the output area. Similarly, the getHeight() and getWidth() buttons can be used to determine the dimensions of such objects.

To determine the endpoints of a Line, you can use the getEnd() and getStart() buttons. You can set the endpoints of a Line using the setEndPoints(...) button. Finally, you can determine the color of any object by clicking on the getColor() button.

As with the other buttons, these buttons correspond directly to operations you can perform within a Java program. We will soon see how information returned by these methods can be used within a program.

Working with Multiple Objects

The remaining method invocation buttons are relevant primarily when you are working with a drawing composed of multiple overlapping objects. To demonstrate, let's create another object.

Create an oval and position it so that it overlaps with your rectangle.

If you entered all the coordinates and dimensions properly, then the image in your drawing area should look something like this:

The new oval is now the selected object. Its bounding rectangle is decorated with eight small black boxes.

You can now use the mouse to change the selected object. Set the color of the oval to magenta by click on setColor(...) and choosing magenta from the list. In addition to being selected, a new object (like the oval) is located logically "above" previously created objects (like the rectangle). Notice that where the rectangle's left edge overlaps the oval, all you see is the magenta interior of the oval, obscuring that part of the rectangle. Since the oval is logically above the rectangle, it hides that part of the edge of the rectangle.

There are buttons in the program's controls corresponding to two methods you can use within a program to alter the logical stacking of graphical objects. They are labeled sendBackward() and sendForward(). To see how they change the stacking:

When multiple objects overlap, you may need to use the send... buttons to change the selected object. If you can't click on the object you would like to select because it is obscured by another object, first select the other object and use sendBackward() to move it beneath the object you wish to select. Then click to select the object you desire.

You can think of each object as being drawn on a separate, large sheet of transparent plastic and the image you see is produced by stacking all these sheets of plastic. Changing the stacking is like pulling out the selected sheet of plastic and moving it up or down the stack.

Hiding and Removing Objects

There are two ways to make an object no longer appear in the canvas: hiding the object and removing the object from the canvas. Hiding the object makes it invisible, but subsequently showing it will make it visible once more. Removing the object permanently removes it from the canvas. We discuss only hiding in today's lab. While both of these options will be available to you when you write programs, only hide and show can be accessed using NotPhotoShop.

So, let's see what happens if we hide the oval. To do this:

Drawing Your Sign

You are now ready to construct a rendition of the no-clicking sign shown at the beginning of this document. The interior of the sign should be colored yellow like a good warning sign. To produce such a sign you will use a FilledRect for the sign's background and a FramedRect for the edge. If you run into problems, ask!

When you are done, DO NOT QUIT THE DRAWING PROGRAM! You will need the picture you have created for the next task.

Writing a Java Program

Now, you will construct a Java program to draw the warning sign you have constructed. You will do this using a program named BlueJ which provides everything you need to type in and run Java programs.

A working solution will appear below. Click inside the applet to interact with it.



To start BlueJ on the Windows systems, open the NoClicking folder that was created in your csis120 folder, then double-click on the package icon.

At this point your BlueJ window should look similar to the image shown below:

This window has three main regions. The bottom-left area is called the instance area. It displays running instances of your Java programs. The bottom-right area is a Java interpreter. This allows you to type in and evaluate Java commands. For now you can ignore both of these areas. The top area displays the names of the Java classes in the project. When there are multiple classes in a project it also displays the relationships of these classes between one another. Each class is really a file. For example, if you click on the NoClicking class, a text-editor will pop-up with the contents of the NoClicking.java file displayed within it. Try it.

The text in the provided NoClicking.java file that should now be on your screen is the skeleton of a complete Java program. It includes the header for the definition of a class NoClicking that extends WindowController and within the class, headers for the event handling methods you will use. However, there are no Java commands within the bodies of these methods, only a Java comment that reminds you when the Java system will follow any instructions you might add to the method body.

You should follow this lead and begin by typing comments rather than actual Java commands. Near the top of the file we have included a temporary comment telling you to enter your name, lab section and the current date. Such identifying comments are always good practice, and in a class like this they make the grader's job much easier. You should find using BlueJ to edit your programs to be similar to using a word processor to edit a paper.

Next, you will add Java instructions to the body of the onMouseClick() method that will draw a "no clicking" warning sign. This is the first method skeleton we have included in the NoClicking class.

As a first step, let's add the single instruction needed to draw the rectangle that frames the contents of the sign. The form of the command you will need to enter is:

new FramedRect(..., ..., ..., ..., canvas);

where all the ...'s need to be replaced by the numbers describing the position and size of the rectangle. This line should be placed immediately after the comment line in onMouseClick() (i.e., just before the line containing the "if}" that ends the method body).

If you remember all the values that should replace our dots, just type them in where we have shown the dots. Otherwise, you can return to the NotPhotoShop program you used in the first part of the lab to determine the values by selecting each object in turn and using the appropriate get...() buttons to display coordinates and dimensions.

Use BlueJ to add a new FramedRect(...) command to your program with the appropriate values. If you have any problems with this step, ask!

Your rectangle constructor should now be below the comment in the onMouseClick() method. Now that it does something, it would be a good idea to update the comment in the onMouseClick() method to say what it does so far. Replace our comment with something more appropriate, like "draws a rectangle when the mouse is clicked." You should get in the habit of updating comments to keep them as accurate as possible as you add instructions to your programs. Not only does this mean you will not have to go back and add comments when you're done, it will help you to remember what everything does as you are writing your programs.

Save your program by selecting "Save" from the "Class" menu. We will now compile the program. To do this, select the "Tools" menu and then "Compile".

Compiling may catch some errors in your program. For example, maybe you forgot to capitalize the first letter of FramedRect. Fortunately, BlueJ highlights the problematic line of code in yellow and displays a specific error message. In the example above, the error message is cannot find symbol - class framedRect. This is example is depicted visually below.

You should fix any problems that BlueJ finds with your code, save your class file, and recompile. If you recompile without saving, BlueJ will automatically save the file for you. Once all the problems are fixed, you can run your program. To do this,

You should see a window appear with the title "panel1". This is your running NoClicking program. Click on the window to bring it into focus. It should appear blank at first. Move the mouse into the window and click. A rectangle should appear because Java invokes your onMouseClick() method, which includes the instruction to construct a rectangle. If this happens, smile. If not, close the display window that popped up when you chose "Run Controller". This will bring you back to the BlueJ project window. Examine the instructions you typed carefully to see if you can find any mistakes. If so, correct them, recompile and run your program again. Otherwise, ask!

When you ask BlueJ to "Run" your program, it starts up a new program that is separate from BlueJ. This is the BlueJ Virtual Machine. While this program is running, you can return to BlueJ by just clicking on any portion of the BlueJ window that is visible on your screen. You should also see a red rectangle in the instance area of the project window. This is because by running the program you created a new instance of the NoClicking class. This instance represents the running program. To avoid confusion, it is a good idea to quit your program by selecting "Quit BlueJ Virtual Machine" before asking BlueJ to run your program again (via the "Run Controller" item).

Once your rectangle program is working, you should add more instructions to it to turn it into a complete warning sign drawing program. Back in BlueJ, immediately beneath the line you added to draw the rectangle, add additional lines to create new Text(...), a new FramedOval(...) and all the other components you created using the NotPhotoShop program. In the NotPhotoShop version of the drawing, we told you to have a yellow background for the sign. Leave that part out of the version your program draws for now; we will add it later. As you work, it is a good idea to compile and run your program every time you add a line or two to ensure that you catch mistakes early. Also, make sure your comment line gets updated by the time you are finished. When you are done, your program should draw a sign when you click in the window, and then do nothing until you tell it to quit. In reality, the program draws another copy of the sign each time you click, but you can't tell, as each new sign is drawn exactly on top of the previous one.

Making Your Program Responsive

Now, to explore event handling methods a bit more, revise your program so that it reacts to the mouse in more interesting ways. In the revised version, the sign will be drawn as soon as the program begins to run. The sign will change, however, as the program runs. In particular, when the user moves the mouse into the program window or presses the mouse, your revised code will alter the appearance of the sign.

Making the program draw the sign when it first starts is easy. You initially placed the code to draw the sign in the onMouseClick() method. There is a skeleton for a method named begin() immediately after the onMouseClick() method definition in the NoClicking class. As you might guess, the instructions in begin() are followed when your program first begins to run. Use cut and paste to move all the drawing instructions from the onMouseClick() method into the begin() method. Don't forget to update your comments. Run your program again. It should display the sign immediately.

Notice that it makes more sense logically to have the begin() method occur before the onMouseClick() method. We arranged them in the opposite order so that you would be able to find onMouseClick() more easily. The point is that the computer does not care which order you write them in your program. Only the names are important (though we urge you to put them in a logical order so that it will be easier for all of us to read!). The order of instructions within a method are important, but the order in which you define the methods within the program is not.

Making the sign change in response to the mouse is a bit trickier. Suppose, for example, that you want to emphasize the sign's warning by changing the color of the word "CLICKING" from black to red when the user moves the mouse into the program's window. As you saw in NotPhotoShop, there is a setColor() operation that you can use to change the color of the text. There is also an obvious place to tell Java to make this change. The onMouseEnter() method is executed whenever the mouse moves into your program window. Placing an appropriate setColor() in that method would do the trick.

The problem is that you can't simply say setColor() in the onMouseEnter() method. If that was all you said, Java would have no way of knowing which of the several objects' color to change. It could change the rectangle, the oval, the text, all of them, etc. Your code has to be more specific and identify the object that should change.

To be able to specify the text object as the object whose color we wish to set, we will have to give it a name. We will use the name message, but we could use any name that seems appropriate.

Associating a name with an object requires two steps. First, we have to include a line that declares or "introduces" the name. This line informs Java that we plan to use a particular name within the program. At this point, we don't need to tell Java which object it should be associated with, but we do need to specify which sort of object it will eventually be associated with. We plan to associate the name message with an object created as new Text(...), so we have to tell Java that the name will be associated with a Text object. The form of a Java declaration is simply the name being declared preceded by the keyword private and by the type of object with which it will be associated. So, the form for our declaration is:

private Text message;

You should add a line containing this declaration to your program immediately before the heading of the onMouseClick() method.

Now you have to tell Java which object to associate with the name message. Your program currently contains a construction of the form:

new Text("CLICKING", ..., canvas);

that creates the text on the screen. To associate the name message with the text object this line creates, revise this line so that it looks like:

message = new Text("CLICKING", ..., canvas);

This is an example of a construct called an assignment statement. It tells Java that in addition to creating the new object, it should associate a name with it. Shortly, you will convert some of your other constructors into assignments.

Now that the text has a name, we can use the name to change its color. Within the body of the onMouseEnter() method add the line:

message.setColor(Color.red);

Then, compile and run your program (correcting any errors as needed).

The program isn't quite complete. It draws the sign immediately and makes the text turn red when the mouse enters the window, but it doesn't make the text black again when the mouse is moved back out of the window. You should be able to figure out what to add to make it black when the mouse exits. Give it a try. Don't hesitate to ask for help if you get stuck.

To get more practice using names and other event handling methods, modify your program a bit more. First, change the program so that while the user is depressing the mouse button, the circle with the diagonal line through the text disappears. (Of course, it should reappear when the mouse is released.) This will require that you declare names for the circle and the line and associate them with the correct objects. These declarations should appear right after the declaration of message. Your code to make the objects disappear and reappear goes in the onMousePress() and onMouseRelease() methods. You can use the hide() and show() methods to handle the disappearing and reappearing. For example, if you called one of your objects myLine, you would hide it with the statement:

    myLine.hide();

Finally, add the yellow background to the sign. We didn't have you do this earlier because you had not yet seen how to associate names with objects. Associate a name with the background rectangle when you create it and then use the name to set its color to yellow. Think carefully about where to put this code so that the shapes are stacked in the right order.

Grading Guidelines

Both functionality and programming style are important when writing code, just as both the content and the writing style are important when writing an essay. In this program, the some of the specific functional requirements we will test for include:

Stylistically, we expect to see programs that exhibit the following:

There is some subjectivity to what makes good style, but the basic goal is to make your ideas as clear and easy to follow as possible.

The last point is worth additional discussion. Often there are several Java commands that can be used to accomplish the same result. It is important to pick the most appropriate commands. For example, in this lab you could make your circle and slash disappear by sending them behind the background, but this would not be the best choice as it is not obvious what your intent is and there is a more direct way of accomplishing the same result.

In general, about half the points in each lab will be for correct functionality and the other half for the style you use in writing the program.

Submitting Your Work

Before the start of your next lab session, submit your Java program for grading. There are three things you need to do to complete the submission: (i) place a copy of your Java program into your csis120/hw folder under hw1, (ii) print a copy of your program and hand it to your lab instructor, and (iii) demonstrate the execution of your program for your instructor.