Bonus Chapter 1: Using Eclipse
Bonus Chapter 1: Using Eclipse
In This Chapter
Understanding Eclipse projects and Workbenches Creating a Java project Compiling, running, and debugging with Eclipse Refactoring with Eclipse
clipse is a development environment that includes many powerful features for creating Java programs. Because Eclipse is free and very powerful, it has become popular among Java developers. In this chapter, you discover the basics of using Eclipse for simple Java development. Because Eclipse is such a powerful tool, it has a steep learning curve. If youre brand new to Java, I suggest that you start out using a simpler environment, such as TextPad (described in Book I, Chapter 3) and turn to Eclipse only after you have your mind around some of Javas programming fundamentals. That way, you start by concentrating on Java programming rather than on mastering Eclipse. When youre ready to get started with Eclipse, go to www.eclipse.org, click the Download Eclipse button, and download the current version of Eclipse IDE for Java Developers. Unlike most programs, Eclipse doesnt have a complicated setup program. You just download the Zip file, extract all the files, and then run the Eclipse executable file (eclipse.exe) directly from the folder you extracted it to. If youre using Windows, you may want to add a desktop shortcut for Eclipse to make it more convenient to start. To do that, open the folder that contains the eclipse.exe file, right-click the file and drag it to the desktop, release the mouse button, and choose Create Shortcut from the menu that appears. Then you can start Eclipse by double-clicking this desktop shortcut. Many of the techniques that I describe in this chapter wont make much sense to you until you know how to use the Java programming features to which they apply. (The information about how to create a new Java class file, for example, wont make much sense until you read about creating Java classes in Book III.) As you find out about Java programming features in later chapters, you may want to refer to this chapter to read about related Eclipse features.
9780470371725-bc01.2.indd BC1
7/12/11 12:11 AM
If you plan on using Eclipse, I suggest that you pick up a copy of Eclipse For Dummies by Barry Burd (Wiley Publishing, Inc.).
9780470371725-bc01.2.indd BC2
7/12/11 12:11 AM
3
Bonus Chapter 1
If you can juggle and chew gum at the same time, you may want to open two Workbench windows so you can work on two projects at the same time. Those of us who have less-than-superhero abilities of concentration can work with just one Workbench window at a time. Editor: An editor is a Workbench pane thats designed for editing a certain type of file. Eclipse comes with a standard text editor that can edit any kind of text file and a special Java editor thats specifically designed for editing Java programs. In Figure BC-1, the Java editor is in the middle portion of the Workbench window. The Java editor in this figure looks small because I captured this screen image with the computers monitor set to 800 x 600 pixels. Because Eclipse puts so much information on the screen, however, running it on a large monitor (preferably 19 inches or larger) at a resolution of at least 1,024 768 is best. That way, the editor window is large enough to let you work with your programs text comfortably while leaving ample room for the other elements displayed in the Eclipse Workbench window. Strictly speaking, an editor is a type of view (covered next in this list). Views: A view is a pane of the Workbench window that displays other information thats useful while youre working with Eclipse. Figure BC-1 shows several views in addition to the editor, such as Package Explorer View, which lets you navigate the various files that make up an Eclipse project, and Problems View, which displays error messages. You can display a view in its own pane or combine it with other views in a single pane, in which the views are indicated by tabbed dividers that you can click to call up each view in the pane. Problems View in Figure BC-1, for example, shares its pane with two other views, called Javadoc and Declaration. Perspective: A perspective is a collection of views designed to help you with a specific type of programming task. The Workbench window pictured in Figure BC-1 shows the Java perspective, which is designed for working with Java program files. Figure BC-2 shows a different perspective, called the Debug perspective. In this perspective, the Java editor is still present, but a different set of views that are useful for testing and debugging Java programs is shown. Console View appears at the bottom of the window so that you can see the output created by the program, and Variables View lets you monitor the contents of variables as the program executes. (For more information about the Debug perspective, see the section Debugging a Java Program, later in this chapter.)
Using Eclipse
9780470371725-bc01.2.indd BC3
7/12/11 12:11 AM
Understanding Projects
Understanding Projects
An Eclipse project is a set of Java files that together build a single Java program. Although some simple Java programs consist of just one file, most real-world Java programs are made up of more than one Java program file. In fact, a complicated Java program may require hundreds of Java program files. When you work on programs that require more than one file, Eclipse lets you treat those files as a single project. A project consists not just of Java source files, but also the class files that are created when you compile the project and any other files that the program requires. Those files might include data or configuration files, as well as read-me files, program documentation, image or sound files, and so on. All the files for a project are stored together in a project folder, which may include subfolders if necessary. In addition to the files required by the program, the project folder includes files that are created by Eclipse to store information about the project itself. A file named .project stores descriptive information about the project, for example, and a file named .classpath stores the locations of the classes used by the project.
9780470371725-bc01.2.indd BC4
7/12/11 12:11 AM
5
Bonus Chapter 1
Using Eclipse
For simple projects that have just a few Java source files, you can create a project that stores all the projects Java files in a single folder. Then, when those files are compiled, the resulting class files are stored in this same folder. This type of project is the easiest to work with, and its ideal for small and medium-size projects. For large projects those that involve dozens or even hundreds of Java source files you can create a project that uses one or more subfolders to store source files. Then youre free to create whatever subfolders you want to help you organize your files. You might create one subfolder for user interface classes, another for database access classes, and a third for image files displayed by the application. Eclipses File menu offers an Open File command, but it isnt very useful. Instead, Package Explorer View (on the left side of the Java perspective; refer to Figure BC-1) displays a list of all the Java projects in your workspace. When you start Eclipse, the project you were working on last appears onscreen automatically. You can switch to a different project by right-clicking the project in Package Explorer View and then choosing Open Project, and you can open an individual file in a project by double-clicking the file in Package Explorer View.
1. Start Eclipse, and click OK when the Workspace Launcher dialog box
appears. The Workspace Launcher dialog box asks for the location of your workspace folder; in most cases, the default location is acceptable. When you click OK, Eclipse opens with the Java perspective, with no projects or files displayed, as shown in Figure BC-3.
9780470371725-bc01.2.indd BC5
7/12/11 12:11 AM
9780470371725-bc01.2.indd BC6
7/12/11 12:11 AM
7
Bonus Chapter 1
Using Eclipse
7. Click Finish.
The HelloApp.java file is created, and Eclipse displays it in the Java editor, as shown in Figure BC-6.
9780470371725-bc01.2.indd BC7
7/12/11 12:11 AM
HelloApp
class.
9780470371725-bc01.2.indd BC8
7/12/11 12:11 AM
9
Bonus Chapter 1
Using Eclipse
HelloApp
program in Eclipse.
9780470371725-bc01.2.indd BC9
7/12/11 12:11 AM
10
3. Click Finish.
A new class file named HelloSayer is created, and Eclipse opens it in a Java editor.
9780470371725-bc01.2.indd BC10
7/12/11 12:11 AM
11
Bonus Chapter 1
Using Eclipse
Check both greeting and addressee in the list of fields to initialize, choose First Method from the Insertion Point drop-down list, select the Omit Call to Default Constructor Super() check box, and then click OK. The following code is inserted into the class:
public HelloSayer(String greeting, String addressee) { this.greeting = greeting; this.addressee = addressee; }
9780470371725-bc01.2.indd BC11
7/12/11 12:11 AM
12
7. Click the HelloApp.java tab at the top of the Java editor pane.
(Refer to Figure BC-8.) The HelloApp.java file comes to the front so that you can edit it.
8. Edit the main method so that it uses the new HelloSayer class.
To do so, delete the code that was in the main method and replace it with this code:
public static void main(String[] args) { HelloSayer h = new HelloSayer(Hello, World!); h.sayHello(); }
The entire HelloApp.java class now looks like Listing BC-2. Eclipse generated all the code except the two lines in the main method.
9780470371725-bc01.2.indd BC12
7/12/11 12:11 AM
Running a Program
13
Bonus Chapter 1
public static void main(String[] args) { HelloSayer h = new HelloSayer(Hello, World); h.sayHello(); } }
Using Eclipse
Running a Program
After you enter the source code for your Eclipse project, you can run it to see whether it works as expected. Eclipse gives you several ways to run a Java program: In Package Explorer View, select the source file for the class you want to run and then choose RunRun AsJava Application. Right-click the source file for the class you want to run and then choose RunJava Application from the shortcut menu that appears. Select the source file in Package Explorer View, click the Run button (shown in the margin), and choose Run AsJava Application from the menu that appears. (If you recently ran the program, you can also choose the program from the list of recently run programs that appears in this menu.) When the program runs, its console output is displayed in a Console View that appears below the Java Editor pane, as shown in Figure BC-9. Note: If the program uses Swing to create a window, that window is displayed separately, not within the Eclipse Workbench window. (See Book VI for more on Swing.) Eclipse is designed so that it automatically compiles Java programs as you work on them. Every time you save a Java source file in Eclipse, the file is automatically compiled to create a class file. As a result, you dont have to compile as a separate step before you can run a program. However, if the project contains large source files, this feature can become annoying. To disable automatic compilation, choose ProjectBuild Automatically to clear the check box next to the Build Automatically option. Then you must build the project manually by choosing ProjectBuild All before you can run it. (To switch back to automatic builds, choose ProjectBuild Automatically again.)
9780470371725-bc01.2.indd BC13
7/12/11 12:11 AM
14
Then the program abruptly stops. Fortunately, Eclipse has a powerful debugger that can help you find the cause of either type of bug and fix it. To start the debugger, run your program by choosing ProjectDebug AsJava Application instead of ProjectRun AsJava Application. Alternatively, click the Debug button in the Workbench toolbar, shown in the margin. Eclipse switches to
9780470371725-bc01.2.indd BC14
7/12/11 12:11 AM
15
Bonus Chapter 1
Debug perspective, as shown in Figure BC-10, and runs the program in debug mode. Note that when you activate the debugger, the Windows firewall may display a security alert. If so, click Allow Access to let the debugger start. Also note that you may want to set a breakpoint in your code before starting the debugger. Otherwise, your program may run to completion and never give you the chance to work in the debugger. You read how to set a breakpoint in the next section, Stepping through your programs. The following sections describe some of the key features of the Debug perspective that are useful for tracking down and correcting bugs in your Java programs.
Using Eclipse
Figure BC-10: Debug perspective lets you debug errant Java programs.
9780470371725-bc01.2.indd BC15
7/12/11 12:11 AM
16
In Eclipse, the Debug View section of Debug perspective is where you control the execution of the program youre debugging. This view displays a tree that indicates each of the threads in your program. (If you dont know what threads are, dont worry about it. Most console-based programs, such as the BugApp program shown in Figure BC-10 earlier in this chapter, use only one thread apiece anyway. In Book V, you find out how to code programs that use more than one thread.) Before you can control the execution of a thread, you must suspend the thread so that its statements stop executing. In general, you can suspend a thread for debugging in three ways: When an unhandled exception occurs, the thread is automatically suspended. In Figure BC-10, the BugApp programs main method is suspended because a divide-by-zero exception occurred, and the program didnt catch it. If your program is throwing an exception that you dont expect, you can simply debug the program and allow the exception to suspend the thread. Then you can try to track down the cause of the problem. Before you debug the program, you can set a breakpoint at any statement in the program. Then, when execution reaches that statement, the thread is suspended. To set a breakpoint, simply double-click the left margin of the Java editor next to the statement where you want the thread to be suspended. I define and discuss breakpoints in detail in the section Setting breakpoints, later in this chapter. If a long-running thread is in a loop, you can suspend it by clicking the thread in Debug View and then clicking the Suspend button (shown in the margin). When you suspend a thread, the statement that will be executed next is highlighted in the Java editor. Then you can continue the threads execution one or more statements at a time by clicking the buttons at the top of Debug View. Table BC-1 describes the most commonly used buttons.
Table BC-1
Button Name Resume
Terminate
9780470371725-bc01.2.indd BC16
7/12/11 12:11 AM
17
Bonus Chapter 1
Button
Description Executes the highlighted statement and then suspends the thread. Skips the highlighted statement, executes the next statement, and then suspends the thread. Executes the highlighted statement, continues executing statements until reaching the end of the current method, and then suspends the thread.
Using Eclipse
Examining variables
When a thread is suspended, you can examine its variables to see whether theyre set to the values you expect. In many cases, you can discover programming errors. If you think that a variable named customerFirstName should contain a customers first name, for example, and it instead contains the name of the state in which the customer lives, you can conclude that you didnt assign the variables value properly. (This situation might be ambiguous if the customer happens to be named Indiana Jones, of course.) The easiest way to examine the value of a variable is simply to point the mouse at the variable in the Java editor. Figure BC-11 shows how the value of the variable i appears when you hover the mouse pointer over it. Here, the pop-up message indicates that the variable i has a value of 0. (This message might be a clue as to why the program has thrown a divideby-zero exception.)
You can also inspect variables by using Variables View, as shown in Figure BC-12. Each variable is listed on a separate line in the top part of Variables View. In addition, the bottom part (called the Detail pane) displays the value
9780470371725-bc01.2.indd BC17
7/12/11 12:11 AM
18
of the currently selected variable. Note that as you step through the various statements in your program, variables appear in Variables View as they are declared and disappear from view when they go out of scope.
Setting breakpoints
A breakpoint is a line in your program where you want the program to be suspended. Setting a breakpoint allows you to efficiently execute the portions of your program that are working properly and stop the program when it reaches the lines that you believe to be in error. All the breakpoints in your program are listed in Breakpoints View, shown in Figure BC-13.
The following paragraphs describe some of the ways you can work with breakpoints in this view: To create a new breakpoint, right-click the vertical bar at the extreme left edge of the code editor window next to the line you want to create the breakpoint for. Then choose Toggle Breakpoint from the shortcut menu that appears. The check box next to each breakpoint indicates whether the breakpoint is enabled. Execution is suspended at a breakpoint only if the breakpoint is enabled.
9780470371725-bc01.2.indd BC18
7/12/11 12:11 AM
19
Bonus Chapter 1
You can delete a checkpoint by clicking the breakpoint to select it and then pressing the Delete key or clicking the Remove Selected button (shown in the margin). You can remove all the breakpoints youve set by clicking the Remove All Breakpoints button (shown in the margin). If you double-click a breakpoint in Breakpoint View, the Java editor window scrolls to the line at which the breakpoint is set. If you want the program to be suspended only after it has hit the breakpoint a certain number of times, right-click the breakpoint and choose Hit Count from the shortcut menu that appears. Then enter the number of times you want the statement to execute before suspending the program, and click OK.
Using Eclipse
9780470371725-bc01.2.indd BC19
7/12/11 12:11 AM
20
Inline: This command is pretty much the opposite of the Extract Method command. It replaces a call to a method with the statements that are defined in the body of that method. This command is most useful when you thought a method was going to be more complicated than it turned out to be, or you thought that youd call it from more locations than you ended up calling it from. Extract Local Variable: This one is weird. Sometimes, you discover that you have a whole string of statements in a row that use a particular expression (say, x + 1). Wouldnt it be better if you just created a separate variable to hold the value x + 1 and then used that variable instead of repeatedly recalculating the expression? The Extract Local Variable command can do this for you. To use this command, highlight the first occurrence of the expression, and choose RefactorExtract Local Variable. Eclipse creates a local variable, adds an assignment statement that assigns the expression to the new local variable, and replaces all occurrences of the expression with the local variable.
9780470371725-bc01.2.indd BC20
7/12/11 12:11 AM