Using Eclipse

Overview

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

  REMEMBER 

Because Eclipse is such a powerful tool, it has a steep learning curve. If you're brand new to Java, I suggest 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 Java's programming fundamentals. That way you start out by concentrating on Java programming rather than on learning Eclipse.

When you're ready to get started with Eclipse, go to the Eclipse Web site (http://www.eclipse.org), click the Download Eclipse button, and download the current version of Eclipse. Unlike most programs, Eclipse doesn't have a complicated setup program. You just download the Eclipse Zip file, extract all the files, and then run the Eclipse executable file (eclipse.exe) directly from the folder you extracted it to.

  Tip 

If you're 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. Then, right-click the file and drag it to the desktop. Release the mouse button and choose Create Shortcut from the menu that appears. You can then start Eclipse by double-clicking this desktop shortcut.

Note that many of the techniques I describe in this chapter won't make much sense to you until you learn how to use the Java programming features they apply to. For example, the information about how to create a new Java class file won't make much sense until you learn about creating Java classes in Book III. As you learn about Java programming features in later chapters, you may want to refer back to this chapter to learn about related Eclipse features.

If you plan on using Eclipse, I suggest 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 development environment, which means that it isn't specifically designed for Java. It's 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. And because Eclipse is most commonly used for Java program development, it comes pre-configured 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:

Figure 4-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 together as a 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. That might include data files or configuration files, as well as other files such as readme files, program documentation, image files, 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 also includes files that are created by Eclipse to store information about the project itself. For example, a file named .project stores descriptive information about the project, and a file named .classpath stores the locations of the classes used by the 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, use File Switch Workspace.

Eclipse lets you create two types of projects:

  Tip 

Eclipse has a File Open File command, but this command isn't very useful. Instead, the Package Explorer View (on the left side of the Java perspective; refer to Figure 4-1) displays a list of all the Java projects in your workspace. When you start Eclipse, the project you were last working on appears on-screen automatically. You can switch to a different project by right-clicking the project in the Package Explorer, and then choosing Open Project. And you can open an individual file in a project by double-clicking the file in the Package Explorer.

Creating a Simple Project

The following procedure takes you step by step 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 4-3.

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

  2. Choose File New Project.

    The New Project dialog box comes up, shown in Figure 4-4. This dialog box lists several wizards you can use to create various types of Eclipse projects.

    Figure 4-4: The New Project dialog box.

  3. Select Java Project from the list of wizards, and then click Next.

    The New Java Project dialog box appears on-screen, shown in Figure 4-5.

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

  4. Type HelloApp in the text box, and then click Finish.

    HelloApp is the project name. 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 both of these options is fine for the HelloApp application.

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

  5. Right-click HelloApp in the Package Explorer View, and then choose New Class from the shortcut menu that appears.

    The New Java Class dialog box opens, as shown in Figure 4-6.

    Figure 4-6: The New Java Class dialog box.

  6. Set the options for the new class.

    In particular:

    • Set the Package text field to JavaAIO.
    • Set the Name text field to HelloApp.
    • 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 4-7.

    Figure 4-7: The newly created HelloApp class.

  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. Choose Run Run As Java Application.

    The program is compiled and run. A console window with the program's output appears at the bottom of the Eclipse window, as shown in Figure 4-8.

    Figure 4-8: The HelloApp program in Eclipse.

      Note 

    If a Save Resources dialog box appears before the program runs, click OK. The program then runs.

Adding a Class File

In this section, I walk you through the process of adding a second class file to the HelloApp application to demonstrate some of Eclipse's most useful features for speeding up Java program development by generating code for commonly used class features.

  Warning 

Unless you've already read Book III, you may get bewildered early on by the code that's presented in this procedure. Don't worry; this code will make complete sense once you read about creating your own classes.

So follow these steps to add a second class to the HelloApp application:

  1. Right-click the JavaAIO branch of the HelloApp project in the Package Explorer and choose New Class.

    The New Java Class dialog box opens (refer to Figure 4-6).

  2. Set the options for the new class.

    For this class, set the options as follows:

    • Leave the Package text field to JavaAIO.
    • Set the Name text field to HelloSayer.
    • Uncheck 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 Source Generate Constructor Using Fields. The Generate Constructor Using Fields dialog box appears, shown in Figure 4-9.

    Figure 4-9: Eclipse can create constructors for you.

    Check both greeting and addressee in the list of fields to initialize, select First Method in the Insertion Point drop-down list, and check the Omit Call to Default Constructor Super() check box. 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 created in Step 5, immediately before the closing brace (}) in the last line of the program:

    public void sayHello() { System.out.println(greeting + ", " + addressee + "!"); }

  7. Click the HelloApp.java tab at the top of the Java editor pane.

    The HelloApp.java file comes to the front so you can edit it.

  8. Edit the main method so that it uses the new HelloSayer class.

    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 4-2. Eclipse generated all the code except the two lines within the main method.

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

Listing 4-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 + "!"); } }

Listing 4-2: The HelloApp Class

package JavaAIO; public class HelloApp { /** * @param args */ public static void main(String[] args) { HelloSayer h = new HelloSayer("Hello", "World"); h.sayHello(); } }

Running a Program

After you enter the source code for your Eclipse project, you can run it to see if it works as expected. Eclipse has several ways to run a Java program:

When the program runs, its console output is displayed in a Console View that appears beneath the Java Editor pane, as shown in Figure 4-10.

Figure 4-10: The Console View displays the program's console output.

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

  Tip 

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 don't usually have to compile as a separate step before you can run a program. If the project contains large source files, this feature can become annoying. To disable automatic compilation, choose Project Build Automatically. Then you must manually build the project by choosing Project Build All before you can run it. (To switch back to automatic builds, choose Project Build Automatically again.)

Debugging a Java Program

No matter how carefully you plan your programs, sooner or later you encounter bugs. You need to watch out for basically two kinds of bugs:

Figure 4-11: The Debug perspective lets you debug errant Java 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.

Stepping through your programs

One of the most basic skills for debugging is executing program statements one at a time. This is called stepping, and it can be a very useful debugging technique. 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 isn't working.

In Eclipse, the Debug View section of the Debug perspective is where you control the execution of the program you're debugging. This view displays a tree that indicates each of the threads in your program. (If you don't know what threads are, don't worry about it. Most console-based programs, such as the BugApp program shown in Figure 4-11, use only one thread apiece anyway. You find out how to code programs that use more than one thread in Book V.)

Before you can control the execution of a thread, you must first suspend the thread so that its statements stop executing. In general, you can suspend a thread for debugging three ways:

When you suspend a thread, the statement that will be executed next is highlighted in the Java editor. Then, you can continue the thread's execution one or more statements at a time by clicking the buttons at the top of the Debug View. Table 4-1 describes the most commonly used buttons.

Table 4-1: Commonly Used Buttons

Open table as spreadsheet

Button

Name

Description

Resume

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

Terminate

Terminates the thread.

Step Into

Executes the highlighted statement, and then suspends the thread.

Step Over

Skips the highlighted statement and executes the next statement, and then suspends the thread.

Run to Return

Executes the highlighted statement and continues executing statements until the end of the current method is reached. Then, the thread is suspended.

Examining variables

When a thread is suspended, you can examine its variables to see if they're set to the values you expect. In many cases, you can discover programming errors. For example, if you think a variable named customerFirstName should contain a customer's first name and instead it contains the name of the state in which the customer lives, you can conclude that you didn't assign the variable's value properly. (Of course, this might be ambiguous if the customer happens to be named Indiana Jones.)

  Tip 

The easiest way to examine the value of a variable is to simply point the mouse at the variable in the Java editor. For example, Figure 4-12 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 divide by zero exception.)

Figure 4-12: Displaying a variable value.

You can also inspect variables by using the Variables View, as shown in Figure 4-13. Each variable is listed on a separate line in the top part of the Variables View. In addition, the bottom part (called the Detail pane) displays the value of the currently selected variable. Note that as you step through the various statements in your program, variables appear in the Variables View as they are declared and they disappear from view when they go out of scope.

Figure 4-13: The 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, while stopping the program when it reaches the lines you believe to be in error.

All the breakpoints in your program are listed in Breakpoints View, as shown in Figure 4-14. The following paragraphs describe some of the ways you can work with breakpoints in this view:

Figure 4-14: The Breakpoints View is where you control breakpoints.

Refactoring Your Code

Refactoring refers to the task of making mass changes to a project. For example, suppose you decide that a class name you created when you started the project doesn't really accurately describe the purpose of the class, so you want to change it. Simple text editors, such as TextPad, 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 different types of refactoring commands. If you're just starting to learn Java, most of these commands won't make any sense to you. For example, the Refactor menu contains commands that let you 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 learning Java. In particular, these:

Категории