0% found this document useful (0 votes)
76 views20 pages

Bonus Chapter 1: Using Eclipse

Eclipse is a powerful integrated development environment for creating Java programs. This chapter discusses how to create and work with projects in Eclipse. It explains that a project in Eclipse contains all the files needed for a Java program and describes how to create a simple one-file Java project in Eclipse by selecting File > New > Java Project and entering a project name. The chapter also provides an overview of key Eclipse concepts like perspectives and views that help organize the Eclipse interface.

Uploaded by

Willy Johnson
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views20 pages

Bonus Chapter 1: Using Eclipse

Eclipse is a powerful integrated development environment for creating Java programs. This chapter discusses how to create and work with projects in Eclipse. It explains that a project in Eclipse contains all the files needed for a Java program and describes how to create a simple one-file Java project in Eclipse by selecting File > New > Java Project and entering a project name. The chapter also provides an overview of key Eclipse concepts like perspectives and views that help organize the Eclipse interface.

Uploaded by

Willy Johnson
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

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

Getting Some Perspective on Eclipse

If you plan on using Eclipse, I suggest that you pick up a copy of Eclipse For Dummies by Barry Burd (Wiley Publishing, Inc.).

Getting Some Perspective on Eclipse


Eclipse is designed to be a general purpose integrated development environment (IDE), which means that it isnt specifically designed for Java. Its like the Seinfeld of IDEs: As its own designers put it, Eclipse is an IDE for anything and nothing in particular. You can easily customize Eclipse with plug-in components called features that make it useful for specific types of development tasks. Also, because Eclipse is most commonly used for Java program development, it comes preconfigured with features designed for developing Java programs. Eclipse uses some unusual terminology to describe its basic operation. These terms, in particular, are worth a look: Workbench: The Workbench is the basic Eclipse desktop environment. When you run Eclipse, the Workbench opens in a window like the one shown in Figure BC-1.

Figure BC-1: The Eclipse Workbench window.

9780470371725-bc01.2.indd BC2

7/12/11 12:11 AM

Getting Some Perspective on Eclipse

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

Figure BC-2: Debugging a program in Eclipse.

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

Creating a Simple Project


All your project folders are stored in a folder called the workspace. Each time you start Eclipse, a dialog box appears, asking for the location of the workspace folder. If you want to change to a different workspace, choose FileSwitch Workspace. Eclipse lets you create two types of projects:

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.

Creating a Simple Project


The following procedure takes you through the process of creating a simple project based on a slightly more complicated version of the Hello, World! program from Book I, Chapter 1. Follow these steps to create this application:

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

Creating a Simple Project

Figure BC-3: Eclipse waits for you to create a project.

2. Choose FileNewJava Project.


The New Java Project dialog box appears, as shown in Figure BC-4.

3. Type HelloApp in the Project Name text box.


The other options in this dialog box let you specify whether the project should be stored in the workspace folder or some other folder and whether the project should use the project folder for source files or create separate subfolders for source files. The default settings for these options are fine for the HelloApp application.

4. Click the Finish button.


When you click Finish, you return to the Java perspective, where HelloApp now appears in Package Explorer View to indicate that youve added a project by that name to your workspace.

5. Right-click HelloApp in Package Explorer View and then choose


NewClass from the shortcut menu that appears. The New Java Class dialog box opens, as shown in Figure BC-5.

9780470371725-bc01.2.indd BC6

7/12/11 12:11 AM

Creating a Simple Project

7
Bonus Chapter 1

Using Eclipse

Figure BC-4: The New Java Project dialog box.

6. Set options for the new class.


For this exercise, set the options as follows: Enter javaAIO in the Package text field. Enter HelloApp in the Name text field. Select the Public Static Void main(String[] args) check box.

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

Creating a Simple Project

Figure BC-5: The New Java Class dialog box.

Figure BC-6: The newly created

HelloApp
class.

9780470371725-bc01.2.indd BC8

7/12/11 12:11 AM

Creating a Simple Project


8. Edit the main method.
Move the insertion point to the empty block for the main method and then edit it to look exactly like this:
public static void main(String[] args) { String[] w = new String[3]; w[0] = Hello; w[1] = , ; w[2] = world!; for (int i = 0; i<3; i++) System.out.print(w[i]); }

9
Bonus Chapter 1

Using Eclipse

9. Choose RunRun AsJava Application.


The program is compiled and run. A console window with the programs output appears at the bottom of the Eclipse window, as shown in Figure BC-7. Note: If a Save Resources dialog box appears before the program runs, click OK. Then the program runs.

Figure BC-7: The

HelloApp
program in Eclipse.

9780470371725-bc01.2.indd BC9

7/12/11 12:11 AM

10

Adding a Class File

Adding a Class File


In this section, I walk you through the process of adding a second class file to the HelloApp application. This second class demonstrates some of Eclipses most useful features for speeding Java program development by generating code for commonly used class features. Unless youve already read Book III, you may get bewildered early on by the code thats presented in this procedure. Dont worry; this code will make complete sense after you read about creating your own classes. Follow these steps to add a second class to the HelloApp application:

1. Right-click the JavaAIO branch of the HelloApp project in Package


Explorer View, and choose NewClass. The New Java Class dialog box opens; refer to Figure BC-5.

2. Set the options for the new class.


For this class, set the options as follows: Leave the Package text field set to JavaAIO. Enter HelloSayer in the Name text field. If it isnt already cleared, clear the Public Static Void main(String[] args) check box.

3. Click Finish.
A new class file named HelloSayer is created, and Eclipse opens it in a Java editor.

4. Add declarations for two public fields named greeting and


addressee. Add these lines immediately after the line that declares the HelloSayer class. Then, other than the comments and the package statement that appears at the beginning of the class, the class looks like this:
public class HelloSayer { private String greeting; private String addressee; }

5. Use a wizard to add a constructor to the class.


To do that, choose SourceGenerate Constructor Using Fields. The Generate Constructor Using Fields dialog box appears, as shown in Figure BC-8.

9780470371725-bc01.2.indd BC10

7/12/11 12:11 AM

Adding a Class File

11
Bonus Chapter 1

Using Eclipse

Figure BC-8: Eclipse can create constructors for you automatically.

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; }

6. Add the code for a method named sayHello.


Add the following code after the constructor you created in Step 5, immediately before the closing brace (}) in the last line of the program:
public void sayHello() { System.out.println(greeting + , + addressee + !); }

The entire HelloSayer class file is shown in Listing BC-1.

9780470371725-bc01.2.indd BC11

7/12/11 12:11 AM

12

Adding a Class File

Listing BC-1: The HelloSayer Class


package JavaAIO; public class HelloSayer { private String greeting; private String addressee; public HelloSayer(String greeting, String addressee) { this.greeting = greeting; this.addressee = addressee; } public void sayHello() { System.out.println(greeting + , + addressee + !); } }

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.

Listing BC-2: The HelloApp Class


package JavaAIO; public class HelloApp { /** * @param args */

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

Debugging a Java Program

Figure BC-9: Console View displays the programs console output.

Debugging a Java Program


No matter how carefully you plan your programs, sooner or later you encounter bugs. You need to watch out for two main kinds of bugs: Incorrect results, such as a program thats supposed to calculate test scores but gives you a C when you score 99 out of 100, or a program thats supposed to calculate sales tax of 5 percent but that says the sales tax on a $29.95 purchase is $149.75 instead of $1.50. Program crashes, such as when a program thats supposed to divide one number into another and print the answer instead prints out this message:
Exception in thread main java.lang.ArithmeticException: / by zero at BugApp.main(BugApp.java:19)

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

Debugging a Java Program

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

Stepping through your programs


One of the most basic skills in debugging is executing program statements one at a time. This technique, called stepping, can be very useful in debugging. By stepping through your program one statement at a time, you can view the effects of each statement and identify the source of errors. Sometimes, just knowing which statements are being executed is all you need to determine why your program isnt working.

Figure BC-10: Debug perspective lets you debug errant Java programs.

9780470371725-bc01.2.indd BC15

7/12/11 12:11 AM

16

Debugging a Java Program

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

Commonly Used Buttons


Description Resumes execution with the next statement. The thread continues executing until it is suspended by an uncaught exception or a breakpoint. Terminates the thread.

Terminate

9780470371725-bc01.2.indd BC16

7/12/11 12:11 AM

Debugging a Java Program

17
Bonus Chapter 1

Button

Name Step Into Step Over Run to Return

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.)

Figure BC-11: Displaying a variable value.

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

Debugging a Java Program

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.

Figure BC-12: Variables View shows the value of each variable.

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.

Figure BC-13: Breakpoints View is where you control breakpoints.

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

Refactoring Your Code

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

Refactoring Your Code


Refactoring refers to the task of making mass changes in a project. Suppose you decide that a class name you created when you started the project doesnt accurately describe the purpose of the class, so you want to change it. Simple text editors such as TextPad (see Book I, Chapter 3) include a Replace command that lets you change occurrences of text strings within a file, but changing the name of a class requires that you change the name in all the files in a project. Eclipse includes a whole menu of refactoring options called, as you might guess, the Refactor menu. This menu contains more than 20 types of refactoring commands. If youre just starting to use Java, however, most of these commands wont make any sense to you. The Refactor menu contains commands that let you do things like change an anonymous inner class to a nested class, push members down to a subclass, or introduce a factory. A few Refactor menu commands are especially useful as you work your way through the basics of Java: Rename: This command lets you rename a variable, method, or other symbol. First, select the symbol you want to rename. Then choose RefactorRename, type the new name, and click OK. Extract Method: This command lets you create a separate method from one or more statements. Select the statements you want to place in the method and then choose RefactorExtract Method. In the dialog box that appears, type the name you want to use for the method, and then click OK. Eclipse creates a method with the statements you selected and replaces the original selection with a call to the new method.

9780470371725-bc01.2.indd BC19

7/12/11 12:11 AM

20

Refactoring Your Code

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy