Appendix A. The Eclipse IDE

In this book, we have tried to focus on the Java language and APIs without spending too much time talking about specific tools. But Java programming today really requires the use of an Integrated Development Envrionment (IDE). Modern languages and develoment tools are intertwined to such an extent that it’s hard to imagine working on large projects without the support of a good IDE. Modern development tools “understand” the language deeply and give you great power to create, search, modify, and fix problems with your code.

A wide array of Java IDEs with varying features are available. Like all power tools, IDEs are constantly changing and improving. Our preferred development environment of many years is Intellij IDEA by JetBrains. However, by far the most widely used IDE for Java is the open source Eclipse project. In the tutorial introduction to this book, we briefly introduced Eclipse. In this appendix, we will go a little farther and use it to load and explore the example code from this book, which have been packaged for you as an Eclipse project.

IDEs offer many benefits as well as a few drawbacks, especially for the new Java programmer. The benefits include an all-in-one view of Java source code with syntax highlighting, navigation help, source control, integrated documentation, building, refactoring, and deployment all at your fingertips. The downside, historically at least, has been that the all-in-one tool tends to become an all-or-nothing tool that locks users into the product and makes them all but helpless without it. IDEs tend to encourage an overly simplistic project layout with no structure or partitioning to help humans understand it. IDEs can also become hairballs of state and information about the project that cannot be easily shared with other developers or across projects. Many of these problems are being addressed by the latest generation of IDEs and for most people, the benefits far outweigh the negatives.

The IDE Wars

Comparing IDEs on features alone is futile because all modern IDEs are based on a plug-in architecture that allows new tools to be added by third parties. Saying that an IDE has feature X is just an invitation for someone to retort that her IDE has plug-ins for X and Y. Still, it is worth taking a moment to draw some comparisons here (if we dare). In this book, we have used both the NetBeans 7.2 and Eclipse 4.2 editors. How do they stack up? The short answer is that, at the time of this writing, Eclipse is more popular and a bit more polished at the expense of being platform-dependent, whereas the latest release of NetBeans offers a few more advanced features out of the box. NetBeans offers a visual application builder and a web application development environment. Of course, you can add those to Eclipse, but you must choose from (possibly pay-ware) alternatives. Another important feature of NetBeans 4.x is that it uses a fully externalized Ant build process. This means that you can build your application inside or outside of the IDE in exactly the same way. With that said, let’s move on to Eclipse.

Getting Started with Eclipse

Let’s get started. First, you’ll need to install Eclipse. Download the latest version of “Eclipse IDE for Java Developers”. Choose the correct version for your platform. Unpack the ZIP file to a location of your choice and then launch the application.

The first time you run Eclipse, you’ll be prompted to select a workspace. This is a root directory to hold new projects that you create within Eclipse. The default location may be inside the application’s install folder itself, which is probably not what you want. Pick a location and click OK.

Eclipse greets you with the Welcome screen. Close this window by closing the Welcome tab within the application. If you want to come back later and go through the Eclipse tutorials and related help topics, you can get this window back by choosing Help Welcome.

One last thing before we move on: Eclipse stores all of its configuration information in the configuration folder inside the Eclipse installation directory. If, at any point in this introduction, you feel that things are not right and you want to start from scratch, you can quit the application and remove this folder. You may also wish to remove your workspace items as they hold per-project state. Less drastically, if you wish to reset all of the application windows to their default locations, you can choose Window Reset Perspective. We’ll talk more about perspectives later.

Importing the Learning Java Examples

Before we talk about the IDE itself, let’s load the examples from this book. You can find a ZIP file containing all of the examples from this book nicely packaged as an Eclipse project at http://oreil.ly/Java_4E. The Eclipse version of the examples is called examples-eclipse.zip.

Open the Import Wizard with File Import and select General Existing Projects Into Workspace as the source and click Next. Choose Select Archive File. Click the Browse button and locate the examples-eclipse.zip file. The Import wizard should look like Figure A-1. Click Finish.

Eclipse will now import all of the files from the archive and immediately begin building the source in the background (a small progress bar at the bottom of the screen will show this).

The import projects dialog box
Figure A-1. The import projects dialog box

Using Eclipse

The first thing we need to do is set up the IDE for browsing and editing our Java source code. If you downloaded the standard Java developer version of Eclipse, it should be set up for Java development. If you chose another package, you may need to select Window Open Perspective Java to put Eclipse into the Java editing perspective. A perspective in Eclipse is an arrangement of different tools, menu bars, and shortcuts geared toward a particular kind of task, such as Java editing or source repository browsing. You can open additional tools and move things around to your liking, but the predefined perspectives give you a good start. Now the Learning Java examples appear in Eclipse, as shown in Figure A-2.

On the left is the Package Explorer. It shows a tree view of the Java packages, libraries, and resources of our project. Click the folder handles to expand the tree and see source folders for each chapter in the book.

The bottom area holds tabs related to Java editing. The tab that is open in Figure A-2, Problems, shows errors and warnings associated with our project code. Eclipse has already compiled our code in the background. In general, you don’t have to tell it to do so. You’ll also notice red Xs on some of the source folders and files. These files have errors. We’ll talk about why some of our examples are being flagged in a moment. The other tabs, Javadoc and Declaration, give information about the file we’re editing or the source code item selected. The Declaration tab can show a preview of the source for an item selected in the main editor window without requiring you to open it explicitly.

To clear up some of those red Xs, we need to make sure that Eclipse is in Java 7.0-compatible mode. Choose Eclipse (or Window) Preferences Java Compiler and set the Compiler Compliance Level to 7.0. Click OK and select Yes to rebuild the source. (It is also possible to set the compiler level on a per-project basis through the project preferences.)

Learning Java examples in Eclipse’s Java editing perspective
Figure A-2. Learning Java examples in Eclipse’s Java editing perspective

If there are still some red Xs left, double-click the README-Eclipse.txt file in the project tree to read the latest explanations for these issues. Some of these issues relate to generating source code or installing additional libraries to make the examples work properly.

Getting at the Source

Let’s navigate to a source file. Go to the Calculator.java file located in the ch19/default package. Double-click it to open the source, as shown in Figure A-3.

When you’re expanding the source folder tree, you can actually continue “deeper” than the Java source file level, expanding elements of the file itself. By moving into the source file in the explorer, you can expose parts of the Java source like methods, variables, and inner classes. By double-clicking these elements, you can open the file and jump right to the corresponding line. This is similar to the outline view that we’ll see in the next section.

Opening Calculator.java
Figure A-3. Opening Calculator.java

The Lay of the Land

In the center of the screen, the open file is displayed in a new editor tab. The editor is, of course, the center of much of the action in a Java IDE. Note the color-coded syntax highlighting. Also, notice the little arrows immediately to the left of the source code. These are folds. A fold groups a section of Java code, such as a Java method or comment, and allows you to collapse or expand it like an outline. For example, the import statements in the file are folded by default. Click the blue arrow to the left of the import line to expand them and see all of the imports.

Next, warnings and errors are highlighted in the column to the left of the folds column. Try making a small error in the file. For example, try changing the javax.swing import to javax.boofa and see what happens. Note all the red Xs indicating problems. When you hover over a red X, you get a pop-up report of the problem. The column on the right of the scrollbar provides a view of the location of warnings and errors. Clicking on these areas takes you to the corresponding line of code. The problems area in the bottom tab is also linked; clicking on a problem report opens the corresponding file at the correct line.

On the right side of the IDE is the outline pane that shows a structured view of the Java code similar to what we saw by expanding the source file tab in the project browser. By clicking on a field, method, or inner class, you jump to the corresponding line in the source editor. Options at the top of the pane let you filter which members are shown for quick access.

Running the Examples

To run the Calculator example, you can simply hit the large green arrow Run button while the source file is open or select the source file in the explorer and choose Run Run As Java Application. The Calculator runs, as shown in Figure A-4.

You may use Run As to tell Eclipse that this file actually is a standalone class with a main() method. Normally, a project has a lot of code and only one or a few main() methods. In that case, the Run menu option (and large green “play” button icon on the toolbar) can be configured to launch the default class for the overall application. An individual file can also be launched from its context menu, which you display by right-clicking on the file (control-click on the Mac). If we had chosen an application that printed output to System.out, Eclipse would have opened a Console tab in the bottom panel to capture the output. To see this in action, run the ch10/PrintfExamples.java example. To run an example that requires arguments, you choose the more general Run option from the Run menu instead. This option pops up a dialog box that lets you configure, among other things, command-line arguments for the launch. The Run menu also includes a Run History option with recent launches so you can run them again quickly.

Running the calculator
Figure A-4. Running the calculator

Building the Ant-Based Examples

Some of the chapters include components that must be built with the supplied Ant build file. For example, the JavaBeans JAR in Chapter 22 and the Web Application WAR file in Chapter 15 have Ant builds. You can run Ant from within Eclipse simply by right-clicking the build.xml file in the folder and selecting Run As Ant Build. However, in order to see it you’ll have to open the Project Explorer using Windows → Show View Project Explorer. (The Project Explorer shows all files in the project as opposed to the view of the Java class hierarchy shown by the Package Explorer.) There are two Ant Build options. The first runs the default target for the build, while the second lets you choose a target (analogous to Run As and Run in the Run menu). For example, to build the magicbeans.jar file from Chapter 22, navigate to sr/ch22/magicbeans/build.xml, right-click, and select Run As Ant Build (the first option). You may have to use the File Refresh option to see new files generated by the Ant build in the project tree.

Loner Examples

Some of the examples in the book may be a little easier to deal with outside of Eclipse, at least until you become immersed in the IDE. For example, some of the networking examples may be more easily run on the command line. There’s no reason to stay in the IDE for everything. Get comfortable in both environments.

Eclipse Features

Eclipse has too many interesting features to really do them justice here, but we’ll mention a few to show you why people love this IDE.

Coding Shortcuts

Of course, you’ve noticed all the color coding and meta-information present when viewing Java source code in Eclipse. You can customize all of this behavior to suit your taste through the Eclipse Preferences Java Editor Syntax Coloring panel. Many other options can be set through the Eclipse Preferences Java Code Style and Editor panes.

What may not be immediately obvious is that editing is also enhanced. When typing, try pressing Ctrl-Space to attempt autocompletion or have Eclipse present you with relevant options. For example, instead of typing JButton, try typing JBu plus Ctrl-Space. Eclipse completes the name for you. If the portion of the name you type is ambiguous, a drop-down list appears, similar to that shown in Figure A-5.

Eclipse also provides abbreviations for common items. Try typing sysout and pressing Crtl-Space. Eclipse expands this to System.out.println() and places the cursor in the parentheses automatically. If you type a quotation mark, Eclipse closes the quotation for you. Note the green bar that it places after the closing quote. Pressing Tab takes you to that point so that you don’t have to use the arrow keys. Pressing Tab again takes you to the next green bar spot, which is the end of the line.

Using completion in Eclipse
Figure A-5. Using completion in Eclipse

Autocorrection

Eclipse can offer fixes for simple problems in your code when it detects them. To see suggested fixes, click on the red X next to a problem line. Eclipse presents a drop-down menu of possible fixes for the problem. Selecting an option shows you the code changes that Eclipse will make before you choose it.

For example, try changing the name of one of the JButtons in our Calculator to JBButton. Now, click the red X and a screen similar to Figure A-6 appears. Eclipse offers several possible corrections; the best one is to fix the misspelling and change it back to JButton. Of course, if we’d really meant to refer to a new kind of button, we could choose the option to create the new class right there and Eclipse would help us do that by creating a skeleton for us.

Autocorrection in Eclipse
Figure A-6. Autocorrection in Eclipse

Refactoring

Eclipse offers a number of tools under the collective title refactoring. These include the ability to rename and move members, automatically tracking down references to them and changing them throughout the project. More advanced options allow you to do things like create an interface for your class by copying all of its public methods or add a factory pattern to your code to encapsulate all object creation for a type. You can even encapsulate access to a variable, changing the code to use an accessor method instead. These tools can save you a lot of typing (or retyping, as the case may be).

As an example, let’s look at our Calculator again. Click on the addGB() method in the outline or select the method definition yourself. We use this method a lot, so let’s give it a better name. Select Refactor Rename and change the name to addToGridBag. If you want to see what it’s going to do in advance, press the preview button to get a diff view of the code. By selecting OK, Eclipse changes the name and all references to the method in your project (in this case that would include all of the source directories for all chapters). You can also refactor methods in order to change the method signature and add or remove arguments.

Diffing Files

Eclipse provides the ability to quickly diff two files. Select two files simultaneously in the Package Explorer. Right-click one of the files to display a context menu and select Compare With Each Other. Eclipse opens a dual-source view editor pane that shows the differences between the files graphically. You can even resolve conflicts by copying differences from one file to the other with the arrows at the top of the pane. For example, open ch15/webapp-xml/all-web.xml and ch15/webapp-xml/filters-web.xml and view the differences. You can also review changes made to a file using the Compare With Local History option that lets you compare the current state of the file with previous saves in the project. These are very useful tools.

Organizing Imports

Eclipse can tidy up the import statements in your source code. Selecting Source Organize Imports causes Eclipse to turn package imports into single class imports. Eclipse automatically determines exactly which classes from each package are used and breaks the package imports into individual imports. This makes the code a little more explicit, but some people prefer package imports when too many classes are used.

Formatting Source Code

Eclipse can autoformat your source code using the Source Format option. This applies standard Java conventions and indentation. The style is highly customizable; choose Window Preferences Java Code Style Formatter to see the available options.

Conclusion

This appendix provides the briefest of introductions to the sorts of things that you can do in Eclipse and other Java IDEs. Please investigate more on your own to learn about what these tools can do to increase your productivity as a Java developer. You should also compare Eclipse, NetBeans, and others such as Intellij IDEA to see which you prefer. And don’t forget to read more about Apache Ant for building Java applications.