CS 124, Spring 2017
Lab 6: Eclipse (and Subroutines)

This lab introduces an "Integrated Programming Environment" (IDE) called Eclipse. Eclipse provides a complete GUI environment for writing, compiling, and running Java programs. It is a free program, but it is one of the most common environments used by professional Java programmers. It is a complex program that can do many things, but you don't have to understand everything that it can do in order to use it effectively. Interestingly, Eclipse is itself written in Java.

There is also a new programming assignment for you to work on. For the assignment, you will write some subroutines to make drawings using "turtle graphics." This is the first time that you have been asked to write complete subroutines from scratch.

You will not need to make a Lab6 folder for use in this lab. Instead, you will create an Eclipse project. Your first task is to learn how to use Eclipse by writing a few very simple programs with it. But in order to complete the programming assignment, you will need copies of three Java files, TurtleGraphics.java, TurtlePanel.java, and TextIO.java. You can find copies in /classes/cs124, as usual, but you will have to work through the lab to find out how to use them in Eclipse.

This lab is due by 3:00 PM next Friday, March 3. You will submit just one file, named TurtleGraphics.java. Be sure to do all five exercises. Submit it using the Submit124 web page, but see the last section of this lab for information about how to find and submit a file from an Eclipse project.

Running Eclipse

This section just describes Eclipse; the next section will tell you how to use it for a programming project. Eclipse is a widely used professional environment for program development. Note that Eclipse and IDEs in general are also discussed in Section 2.6 of the textbook. Eclipse is already installed on the Linux computers that you will use during the lab. You can access it in the "Programming" sub-menu of the application menu. You might want to add an "Eclipse" button to the panel at the top of the screen to make it easier to get to. To do that, simply right-click the "Eclipse" item in the menu, and select "Add to Panel".

Although it is not required for the course, You might consider running Eclipse on your own computer as well. It is available for Linux, Windows, and Mac OS. You can download the most recent version of the Eclipse installer from the Eclipse downloads page at eclipse.org. You should get the "Eclipse IDE for Java Developers". Note that you need to have Java on your computer before you install Eclipse, since Eclipse is itself written in Java. If you would like some help installing Java or Eclipse on your computer, ask for it.

Eclipse organizes your programming projects into "workspaces." A workspace is really just a directory, and a project is a subdirectory inside that directory. A project holds the files relevant to a given programming project, such as Java source code files, compiled class files, and data files. You should let Eclipse have complete control over the workspace directories, and you should not directly change any files that are stored in them. It is possible to have as many workspaces as you want, but for this course, you will probably keep all of your projects in the same workspace. (In fact, you can keep all the programs that you ever write in one workspace, if you want.)

When Eclipse starts up for the first time, it asks you to select a workspace. (There is a box that you can check if you don't want to be asked to select a workspace each time you run Eclipse.) By default, the name of the workspace will be "workspace", but you can change the name if you want. For example, you might to name it "workspace-cs124".

When the Eclipse window first opens, it will be filled with a "Welcome" screen. The icons on this screen link to a large amount of information about Eclipse. You can browse through this information some time, if you like, but for now, just close the Welcome screen by clicking the "×" next to the word "Welcome" near the top left corner of the window. To avoid seeing the Welcome screen every time you start Eclipse, uncheck the box labeled "Always show Welcome at startup" at the bottom left corner of the Welcome screen.

Eclipse uses the terms view and perspective to describe the way that information is organized and presented in its window. A "view" is one of the panels in a "perspective." The window typically contains several views. Each view contains a certain type of information. All the views that are visible in the window constitute a perspective. A perspective is meant to contain all the views that are used in some particular activity. For now, you will just use the Java perspective, which is organized for Java programming. Each perspective is highly customizable. You can add and delete views and move them around. If you ever delete a view accidentally, you can get it back by selecting it from the "Show View" submenu in the "Window" menu. If you mess up a perspective, you can get back the original, default setup with the "Reset Perspective" command in the "Perspective" submenu of the "Window" menu.

After you have closed the Welcome screen, the window will show the Java perspective. Initially, all the views are empty. Here is what the Java perspective might look like after a little work has been done:

Eclipse Window showing Java Perspective

In this window, I have closed a couple of the views that I don't use: the "Task List" and "Outline" views, which originally appeared on the right edge of the window. Remember that a view can be closed by clicking the small "×" next to the name of the view, and it can be reopened using the "Window" / "Show View" menu.

The "Package Explorer" view, on the left, is central to much of the work that you do in Eclipse. It contains a list of your programming projects and the Java files and resources that are contained in those projects. In the above picture, there is just one project, named Lab6. Clicking on the small triangle (or plus sign) next to the project name will show/hide the resources contained in the project. In a new project, there will be a directory named src where the source files for the project will be stored. Inside the src folder, you will see Java files organized into packages. In this course, we will only use the "default package," as shown in this example.

The lower right section of the window contains several views. In the picture, the "Console" view is showing. To see one of the other views, such as "Problems" or "Javadoc", just click on the tab that contains the name of the view. Sometimes, another view will pop up automatically in this area to show the output of some command. When you run a program, standard input and output are done in the "Console" view. Errors and warnings from the Java compiler are displayed in the "Problems" view.

The central area of the window is occupied by editor views. Here, I've created a Java file, HelloFromEclipse.java, and have opened it for editing. Another source file, named TurtleGraphics.java, has also been opened and is in another tab.

The view of HelloFromEclipse.java shows several of the nifty features of the Java editor. The source code that you type is checked for syntax errors as you type. Errors are marked with small red carets at the bottom of the line. The error is also marked by a red rectangle in the right margin of the editor and sometimes by an icon in the left margin of the editor; if you hover your mouse over any error or error marker, you see an error message for the error. For the first error in the picture, for example, you would be told that a semicolon is missing. In the third line of main(), the word "printnl" is underlined with error markers. (It's a misspelling of "println".) This error has an error light bulb () in the left margin of the editor. The light bulb means that Eclipse is not just telling you about the error but is offering you some ideas for fixing it. If you click the light bulb, you get a list of actions that can be taken to fix the problem. You will also see the list if you hover the mouse over the underlined error itself. For the example, here is what I get when I hover the mouse over the incorrect word "prin":

change to print(), and other options

Clicking on an action, such as "Change to print()", will apply that option automatically. Sometimes, you will see a warning light bulb (). A warning indicates a potential problem, but not an error. Warnings will not prevent the source code from being compiled successfully.

In fact, Eclipse might be a little too enthusiastic in marking warnings and errors! You do not necessarily have to fix every warning. And you do not have to fix every error as soon as it appears. In fact, it's impossible to do so. In some cases the error will go away by itself after you've typed in more of your program. And remember that the fix for a programming error does not always go at the location of the error; sometimes the problem is elsewhere in the file. Furthermore, Eclipse's error system is only effective if you routinely get most of your program correct in the first place — don't expect Eclipse to make solid Java programming skills unnecessary!

In fact, many of the fixes that Eclipse will offer will do things to your code that you won't understand. Not every fix is a good idea! Don't let Eclipse fix your code unless you understand what it wants to do and why!

Note that Eclipse will even spell-check your comments. It will mark a misspelled word in a comment with a red underline. If you hover the mouse over a misspelled word, you will get a list of possible corrections. Click an item in this list to apply the correction to the word.

Your First Eclipse Project

It's time for you to start using Eclipse. Start up Eclipse, as described above. Close the "Welcome" screen (and probably the "Task List" and "Outline" views as well). You will create a project just like the one shown in the above illustrations.

To create your project, right-click in the "Project Explorer" pane on the left edge of the Eclipse window. In the pop-up menu that appears, go to the "New" submenu, and select "Java Project." (Alterntively, select "New" / "Java Project" from the "File" menu.) A "New Project" wizard will pop up. All you have to do is enter a name for the project, in the box labeled "Project Name". Enter Lab6 or any other name as the name of the project. After entering the project name, click the "Finish" button. The project will be added to "Project Explorer", and a directory of the same name will be created in your Eclipse workspace directory.

In general, you will create some new Java classes, and you will also import some existing files into your project. For this example, you should import the three required files, TurtleGraphics.java, TurtlePanel.java, and TextIO.java.

To import the files: Open a file browser window in which you can see the files. (Browse to /classes/cs124.) In the Eclipse window, click the triangle next to the project name (such as "Lab6"), so that you can see the folder labeled "src". You can then use Copy-and-Paste to copy the files from the file browser window into the src folder in Eclipse. (That is, right-click a file in the file browser window, select "Copy", then right-click the src folder in the Eclipse window and select "Paste".) Alternatively, you can drag files from the file browser window onto the src folder in the Eclipse window. When you do that, you will be asked whether you want to "Copy" or "Link" the files. Choose "Copy." Copies of the files will be added to the project.

After adding the files, if you click the triangle next to "src", you should see that the three Java files have been placed into the "(default package)". To open a file in the Eclipse editor, just double-click its name in the Package Explorer view.

You need to learn how to create a new class in Eclipse!: Right-click the project name in the "Package Explorer" view. In the pop-up menu, go the "New" submenu again, and select "Class":

menus for creating a class

A class creation dialog box will pop up. Again, you just have to fill in the name of the class, and click the "Finish" button. Note that you have to enter the name of the class, not the name of the file, so don't try to add a ".java" extension to the name. The name must be a valid Java class name. Use any name you like for the class name, since you will not turn in the class. The Java file will be added to the src folder in your project, in the "default package." Furthermore, a Java editor will open, showing you the initial contents of the file. As you will see in the editor window, Eclipse has already added the declaration of the class. All you have to do is fill it in! Note that you can close the editor in the usual way by clicking the little ×. To open the file again, double-click its name in the "Project Explorer."

Eclipse often has alternative ways of doing things. Another way to create a class is with a button in the toolbar. Look for the group of two small buttons at the top of the Eclipse window:

buttons for creating packages and classes

Click the button on the right in this group to create a new class. (When you create a class using the button, you should first click in the Package Explorer to select the location of the class that you are creating. Otherwise, you'll have to enter the location by hand in the class creation dialog box.)

I strongly suggest that you try typing a short program into the new class, to get some experience with programming in Eclipse.

In Eclipse, you don't have to do anything to complile a program, since that is done automatically. To run a program, right-click either on the name of the class in the "Project Explorer" or on the editor window that contains the program. In the pop-up menu, go to the "Run As" submenu, and select "Java Application" from the submenu. The program will start. The output from the print statements appears in the "Console" view in the bottom right area of the Eclipse window. In order to type a response, you must first click the Console window! Type in your response and press return.

For another way to run a program, if an editor window for the program is currently the selected view, you can run the program by clicking on the "Run" button (run button) in the toolbar. If you click the little black triangle to the right of the "Run" button, you'll get a list of all the programs that you have run; select a program from this list to run it.

At this point, you might experiment more with Eclipse, or you might just go on to work on the programming assignment later in this lab.

You have surely already noticed that the Java editor in Eclipse does a certain amount of work for you. It automatically inserts indentation. When you type a "{" and press return, the matching "}" is inserted in the correct position. Furthermore, when you type a period, a list of things that can follow the period will pop up, and you can select an item from the list instead of typing it in. This is called Content Assist. You can invoke Content Assist at any time while you are typing by pressing Control-Space. If you do this in the middle of a variable name or method name, pressing Control-Space will either complete the name or offer a list of possible completions. It can be used in other ways as well. For example, if you press Control-Space after typing the "(" at the beginning of a method's parameter list, you will get information about the parameters of the method. By the way, when Content Assist pops up a list, you can get rid of the list by pressing the Escape key.

Content Assist is a good thing, but I find the way it pops up automatically while I am typing to be rather annoying. You can turn off this feature in the Eclipse Preferences. Select the "Preferences" command from the "Window" menu. In the Preferences dialog box, click the little triangle next to "Java" to open the list of Java preferences (if necessary), then click the triangle next to "Editor", and finally click on "Content Assist." In the Content Assist preferences, uncheck the box labeled "Enable Auto Activation" and click "OK".

Eclipse has a huge number of preference settings that can be used to customize the environment. Most of the default settings are OK, but there are a few that I usually change. If you want to do the same: Under "Java / Editor / Mark Occurrences", turn off "Keep marks when the selection changes". Under "Java / Compiler / Errors/Warnings / Potential Programming Problems", change "Serializable class without serialVersionUID" from Warning to Ignore, and change "Possible accidental boolean assignment", "'Switch' case fall-through" and "Null reference" from Ignore to Warning.)

Eclipse has a lot of other useful features. We will encounter more of them as time goes on, and you can undoubtedly discover a few new ones on your own. But here are a few of the most useful:

About The Turtle in Turtle Graphics

The programming assignment for this week uses Turtle Graphics. If you followed the instructions above, you have already added TurtleGraphics.java and TurtlePanel.java to your Eclipse project. You will edit TurtleGraphics.java. TurtlePanel.java defines the turtle graphics methods that are used in the program. Do not make any changes to TurtlePanel.java; your program must work with the original version.

The file TurtlePanel.java defines a screen area that represents the turtle habitat. The habitat has x-coordinates that range from -10 on the left to 10 on the right, and it has y-coordinates that range from -10 on the bottom to 10 at the top. (These coordinates are real numbers and they are not the same as pixel coordinates.) The turtle starts out in the center, at (0,0), facing to the right. The turtle has a "pen" that can be raised or lowered. If the pen is down when the turtle moves, it leaves a trail: The pen draws a line from the starting point to the point to which the turtle moves.

TurtleGraphics has a variable named turtle. You give commands to the turtle by calling methods in turtle such as turtle.forward(5), turtle.turn(45), and turtle.penUp(). To learn about all the available methods, you can read the source code file, TurtlePanel.java. But here is a list that includes all the commands that you might need for this lab.

The Programming Assignment

You should be editing TurtleGraphics.java in Eclipse. The main() routine in that program runs in a loop in which it asks the user to select an action and then carries out the action. Run the program, and move the Eclipse window so that you can see both the Turtle Graphics window and the Eclipse window. The program presents a menu of three possible actions, numbered 1 to 3. The user responds by entering a number. A switch statement is used to carry out the user's command. Currently, commands number 2 and 3 tell the program to call subroutines named drawRect and drawSquareSpiral. These subroutines are defined below main().

To interact with the program, you must first click in the Eclipse console. Do that now, and try commands 2 and 3.

Your assignment for this lab will be to write several more subroutines and to add commands to main() that will call the subroutines that you write. There are five exercises. Be sure to do them all.

Exercise 1: Write a subroutine that will draw a blue triangle inside a red triangle, as shown at the right. Remember that the definition of a subroutine cannot be inside another subroutine. Other than that, it can be anywhere in the class. You can imitate the definition of drawSquareSpiral. In your subroutine, use only turtle.forward, turtle.back, turtle.turn, and commands for setting color and maybe line width. The subroutine has no parameters. The size and position of the big triangle are up to you. Add command number 4 to the main() routine for calling the subroutine. That means that you must add a line of output to the menu such as

System.out.println("   4.  Draw a triangle in a triangle.");

Furthermore, you must add a "case 4" to the switch statement. You can imitate what is done for the other cases. It is important that the case end with a break statement. After adding the new case, the switch will look like this, except possibly for the name of the new subroutine:

switch (choice) {
case 1:
    System.exit(0);  // End the program
case 2:
case 3:
case 4:
   System.out.println(choice + " is not a legal choice!  Try again.");

You should add a similar option to the menu for each subroutine that you write.

Exercise 2: For your second exercise, you should write a subroutine that draws a set of at least three nested squares, as shown in the picture. This time, you can use any turtle commands that you want, but you must use the drawRect subroutine to draw the actual squares. Again, this subroutine has no parameters. The size, colors, and position of the drawing are up to you. Use random colors if you like. You will need to use turtle.penUp() and turtle.penDown() to make it possible to move the turtle without drawing a line. (You might try drawing a larger number of squares using a for loop, but you are not required to use a loop.)

Exercise 3: Most subroutines have parameters. For this exercise, you will write a subroutine with one parameter, of type int. The subroutine should draw a picture similar to the one shown at the right. The parameter specifies the number of lines in the picture. All the lines should radiate from the current turtle position. Use a for loop to draw as many lines as the parameter specifies. Note that you can say "turtle.forward(length); turtle.back(length);" to a draw line of a given length along the direction in which the turtle is pointing and then return to the starting point of the line (ready to change the direction and draw the next line). The length should be chosen at random. You can either use turtle.face to point the turtle in random directions, or use turtle.turn to turn a small amount between each line and the next.

The main() routine should, of course, have a command to call your subroutine. But you might want to have a second command to draw several groups of lines at different positions and with different numbers of lines in each group. To do that, you will need several statements in the switch statement's case.

Exercise 4: Write a subroutine that sends the turtle on a random walk. The idea is to do the following over and over: Select one of the directions 0, 90, 180, or 290 at random; face in that direction; then move forward by a small, constant amount (say 0.25). Here is a loop that does this forever:

while (true) {
    int direction;
    direction = 90 * (int)(4*Math.random());

A sample random walk created by this code is shown in the picture on the right. One could just put the code into a subroutine. However, you should write a random walk subroutine that has a parameter. What the parameter does is up to you. The parameter could be the distance that the turtle moves forward in each step. Or the parameter could specify the number of steps that the turtle will take, instead of letting it walk forever. Another idea is to implement two different kinds of random walk, and use a boolean parameter to tell the subroutine which kind of walk to do. You can get a nice pattern by selecting the direction randomly from 0, 60, 120, 180, 240, 300 instead of from 0, 90, 180, 270. A different sort of random walk is obtained by facing in a completely random direction and moving forward a random amount each time. Another idea is to use a random color for each step in the random walk.

(Note: An infinite loop is a bad idea in this program, since there will be no way for the subroutine ever to return to main()! If the random walk uses an infinite loop, then the turtle will eventually wander off the screen. If you want to detect when that happens and end the loop at that point, note that there are functions turtle.getTurtleX() and turtle.getTurtleY() that return the current x- and y-coordinates of the turtle. And remember that coordinates on the visible window extend from -10 to 10.)

Exercise 5: The final exercise is to write at least one additional drawing subroutine of your own design. The subroutine should have at least one parameter. Try to do something interesting or attractive!

About Comments

Every subroutine that you write should have a comment. The comment should come immediately before the subroutine definition, and is should typically start with /** and end with */. Comments that start with /** are "JavaDoc" comments, and they should follow a certain format. You are not responsible for following the exact format for now, but you should still use /** for the comments on your subroutines. Note that in Eclipse, if you click the line before a subroutine definition, type /**, and press return, the Eclipse will add an outline of a JavaDoc-style comment.

(Javadoc is discussed in Section 4.5.4 of the textbook. For now, you can just imitate the comments on the subroutines that were already provided in the program.)

Turning in Your Work

You will turn in your work as usual, using the web page at http://math.hws.edu/submit124. There is only one file to submit this week: TurtleGraphics.java. The only problem is how to find the file on your computer.

The file is in the Eclipse workspace that you created the first time Eclipse started up. The workspace is a director, which is in your home directory unless you specified a different location.

To find your file: Open the Eclipse workspace in a file browser window. Inside, you will find a folder with the same name that you used for the project in Eclipse. Inside that folder is a folder named src. And the Java files for your project are in that src folder. When you submit TurtleGraphics.java, you will have to browse to that src folder to find it.