2Getting started with the Eclipse Workbench

2Getting started with the Eclipse Workbench
Getting started with
the Eclipse Workbench
In this chapter…
Downloading and installing Eclipse
Essential Eclipse Workbench concepts, including
perspectives, views, and editors
Creating, running, and debugging a Java
Customizing Eclipse preferences and settings,
including code format style and classpath
Creating and modifying code generation
Eclipse Workbench
Getting started is often the hardest part of a journey. Mostly this isn’t due to any
real obstacle, but rather to inertia. It’s easy to get set in your ways—even when
you know that adventure waits. Eclipse is the new land we'll be exploring here.
After downloading Eclipse and getting your bearings, you’ll find that you’ll soon
be on your way, coding and debugging with ease.
2.1 Obtaining Eclipse
The first step toward getting started with Eclipse is to download the software
from the Eclipse.org web site’s download page at http://www.eclipse.org/
downloads. Here you’ll find the latest and the greatest versions—which are not
usually the same things—as well as older versions of Eclipse. Basically, four types
of versions, or builds, are available:
Release—A stable build of Eclipse that has been declared a major release by
the Eclipse development team. A release build has been thoroughly tested
and has a coherent, well-defined set of features. It’s equivalent to the
shrink-wrapped version of a commercial software product. At the time of
this writing, the latest release is 2.1, released March 2003; this is the release
we will be using throughout this book.
Stable build—A build leading up to a release that has been tested by the
Eclipse development team and found to be relatively stable. New features
usually first appear in these intermediate builds. These builds are equivalent to the beta versions of commercial software products.
Integration build—A build in which Eclipse’s individual components are
judged to be stable by the Eclipse developers. There is no guarantee that
the components will work together properly, however. If they do work
together well, an integration build may be promoted to stable build status.
Nightly build—A build that is (obviously) produced every night from the latest version of the source code. As you may guess, there are absolutely no
guarantees about these builds—in fact, you can depend on their having
serious problems.
If you are at all risk-averse (perhaps because you are on tight schedule and can’t
afford minor mishaps), you’ll probably want to stick to release versions. If you are
a bit more adventurous, or must have the latest features, you may want to try a
stable build; the stable builds immediately before a planned release build usually
offer the best feature-to-risk ratio. As long as you are careful to back up your
workspace directory, these are a fairly safe bet. You can find out more about the
Eclipse overview
Eclipse team’s development plans and the development schedule at http://
After you choose and download the best version for you, Eclipse installation
consists of unzipping (or untarring, or whatever the equivalent is on your platform) the downloaded file to a directory on your hard disk. Eclipse, you’ll be
happy to learn, won’t infect your system by changing your registry, altering your
environment variables, or requiring you to re-boot. The only drawback is that
you’ll have to navigate your filesystem searching for the Eclipse executable to
start it. If you don’t want to do this each time you use Eclipse, you can create a
shortcut to it, or put it on your path. For example, in Windows, after you find the
Eclipse executable (eclipse.exe) using the Windows Explorer, right-click on it and
select Create Shortcut. Doing so will create a shortcut in the Eclipse directory
that you can drag to your desktop or system tray. On UNIX and Linux platforms,
you can either add the Eclipse directory to your path or create a symbolic link
(using ln –s) for the executable in a directory already in your path (for instance,
2.2 Eclipse overview
The first time you start Eclipse, it will ask you to wait while it completes the installation. This step (which only takes a moment) creates a workspace directory underneath the Eclipse directory. By default, all your work will be saved in this directory.
If you believe in backing up your work on a regular basis (and you should), this is
the directory to back up. This is also the directory to take with you when you
upgrade to a new version of Eclipse.
You need to check the release notes for the new release to make sure it supports workspaces from prior versions; but barring any incompatibility, after you
unzip the new version of Eclipse, simply copy the old workspace subdirectory to
the new Eclipse directory. (Note that all your preferences and save perspectives
will also be available to you, because they are stored in the workspace directory.)
2.2.1 Projects and folders
It’s important to know where your files are located on your hard disk, in case you
want to work with them manually, copy them, or see how much space they take
up. However, native filesystems vary from operating system to operating system,
which presents a problem for programs that must work consistently on different
operating systems. Eclipse solves this problem by providing a level of abstraction
above the native filesystem. That is, it doesn’t use a hierarchy of directories and
Eclipse Workbench
subdirectories, each of which contains files; instead, Eclipse uses projects at the
highest level, and it uses folders under the projects.
Projects, by default, correspond to subdirectories in the workspace directory,
and folders correspond to subdirectories of the project folder; but in general,
when you’re working within Eclipse, you won’t be aware of the filesystem. Unless
you perform an operation such as importing a file from the filesystem, you won’t
be exposed to a traditional file open dialog box, for example. Everything in an
Eclipse project exists within a self-contained, platform-neutral hierarchy.
2.2.2 The Eclipse Workbench
Eclipse is made up of components, and the fundamental component is the Eclipse
Workbench. This is the main window that appears when you start Eclipse. The
Workbench has one simple job to do: to allow you to work with projects. It doesn’t
know anything about editing, running, or debugging Java programs; it only
knows how to navigate projects and resources (such as files and folders). Any tasks
it can’t handle, it delegates to other components, such as the Java Development
Tools (JDT).
Perspectives, views, and editors
The Eclipse Workbench is a single application window that at any given time
contains a number of different types of panes called views plus one special pane,
the editor. In some cases, a single pane may contain a group of views in a tabbed
notebook. Depending on the perspective, one pane might contain a console window while another might contain an outline of the currently selected project.
The primary component of every perspective, however, is the editor.
Just as there are different types of documents, there are different types of editors. When you select (or create) a document in Eclipse, Eclipse does its best to
open the document using the most appropriate editor. If it’s a simple text document, the document will be opened using Eclipse’s built-in text editor. If it’s a Java
source file, it will be opened using the JDT’s Java editor, which has special features
such as the ability to check syntax as code is typed. If it’s a Microsoft Word document on a Windows computer and Word is installed, the document will be opened
using Word inside Eclipse, by means of object linking and embedding (OLE).
You don’t directly choose each of the different views in the Workbench or how
they are arranged. Instead, Eclipse provides several preselected sets of views
arranged in a predetermined way; they are called perspectives, and they can be
customized to suit your needs.
Eclipse overview
Every perspective is designed to perform a specific task, such as writing or
debugging a Java program, and each of the views in the perspective is chosen to
allow you to deal with different aspects of that task. For example, in a perspective
for debugging, one view might show the source code, another might show the
current values of the program’s variables, and yet another might show the program’s output.
The first time you start Eclipse, it will be in the Resource perspective (see figure 2.1). You might think of this as the home perspective. It is a general-purpose
perspective useful for creating, viewing, and managing all types of resources—
whether a resource is a Java project or a set of word-processing documents doesn’t
matter in this perspective, apart from which editor is used to open specific documents in the editor area.
The panel at upper left is called the Navigator view; it shows a hierarchical
representation of your workspace and all the projects in it. At first this view will
Figure 2.1 The initial view of Eclipse is the Resource perspective—a general-purpose perspective
for creating, viewing, and managing all types of resources.
Eclipse Workbench
be empty, of course; but, as you’ll see, it is the starting point for creating projects
and working with Eclipse.
Within the Workbench, as you work, you can choose among the different perspectives by selecting Window→Open Perspective. Eclipse will also change the
perspective automatically, when appropriate—such as changing from the Java
perspective to the Debug perspective when you choose to debug a program from
the Eclipse menu.
Menus and toolbars
In addition to perspective, views, and editors, several other features of the Workbench user interface (UI) are worth mentioning: the main menu, the main toolbar,
and the shortcut toolbar. Like the views and editors in a perspective, the Workbench’s menu and toolbar can change depending on the tasks and features available in the current perspective.
The Eclipse main menu appears at the top of the Workbench window, below
the title bar (unless you are using a Macintosh, in which case the menu appears,
Mac style, at the top of the screen). You can invoke most actions in Eclipse from
the main menu or its submenus. For example, if the document HelloWorld.java
is currently being edited, you can save it by selecting File→Save HelloWorld.java
from the main menu.
Below the main menu is a toolbar called the main toolbar, which contains buttons that provide convenient shortcuts for commonly performed actions. One,
for example, is an icon representing a floppy disk, which saves the contents of
the document that is currently being edited (like the File→Save menu selection).
These tool buttons don’t display labels to indicate what they do unless you position the mouse pointer over them; doing so causes a short text description to
display as a hovering tool tip.
Along the left side of the screen is another toolbar called the shortcut toolbar.
The buttons here provide a quick way to open a new perspective and switch
between perspectives. The top button, Open a Perspective, is an alternative to
the Window→Open Perspective selection in the main menu. Below it is a shortcut to the Resource perspective. As you open new perspectives, shortcuts to those
perspectives appear here, as well.
You can optionally add another type of shortcut to the shortcut toolbar: a Fast
View button. Fast Views provide a way to turn a view in a perspective into an icon—
similar to the way you can minimize a window in many applications. For example, you may find that in the Resource perspective, you need to look at the Outline view only occasionally. To turn the Outline view into a Fast View icon, click
Eclipse overview
on the Outline icon in the view’s title bar and select Fast View from the menu that
appears. The Outline view is closed, and its icon appears in the shortcut toolbar.
Clicking on the icon alternately opens and closes the view. To restore the view in
its previous place in the perspective, right-click on the Fast View icon and select
Fast View.
In addition to the Workbench menu and toolbars, views can also have
menus. Every view has a menu you can select by clicking on its icon. This menu
lets you perform actions on the view’s window, such as maximizing it or closing
it. Generally this menu is not used for any other purpose. Views can also have a
view-specific menu, which is represented in the view’s title bar by a black triangle. In the Resource perspective, the Navigator view has a menu that lets you set
sorting and filtering options.
Some views also have a toolbar. In the Resource perspective, the Outline view
has tool buttons that let you toggle various display options on or off.
Changing perspectives
As you work in the Eclipse Workbench, you’ll occasionally find that the different
views aren’t quite the right size for the work you’re doing—perhaps your source
code is too wide for the editor area. The solution is to click on the left or right
window border and drag it so the window is the right size.
Sometimes you may want to supersize a view temporarily by double-clicking on
the title bar; this will maximize it within the Eclipse Workbench. Double-clicking
on the title bar again will reduce it back to its regular size.
You can also move views around by dragging them using their title bars. Dragging one view on top of another will cause them to appear as a single tabbed notebook of views. Selecting a view in a notebook is like selecting a document in the
editor pane: Click its tab at the top or bottom of the notebook. Dragging a view
below, above, or beside another view will cause the views to dock—the space occupied by the stationary view will be redistributed between the stationary view and
the view you are dragging into place. As you drag the window you want to move,
the mouse pointer will become a black arrow whenever it is over a window boundary, indicating that docking is allowed. For example, if you want to make the editor area taller in the Resource perspective, drag the Task view below the Outline
view so the Navigator, Outline, and Task views share a single column on the left
side of the screen.
In addition to moving views around, you can remove a view from a perspective
by selecting Close from the view’s title bar menu. You can also add a new view to
a perspective by selecting Window→Show View from the main Eclipse menu.
Eclipse Workbench
Eclipse will save the changes you make to perspectives as you move from perspective to perspective or close and open Eclipse. To restore the perspective to
its default appearance, select Window→Reset Perspective.
If you find that your customized perspective is particularly useful, you can
add it to Eclipse’s repertoire of perspectives. From the Eclipse menu, select
Window→Save Perspective As; you will be prompted to provide a name for your
new perspective.
2.3 The Java quick tour
Eclipse is installed, and you understand how the different views in perspectives
work together to allow you to perform a task. Let’s take Eclipse out for a spin by
writing, running, and debugging a traditional “Hello, world” program.
2.3.1 Creating a Java project
Before you can do anything else in Eclipse, such as creating a Java program, you
need to create a project. Eclipse has the potential to support many kinds of
projects using plug-ins (such as EJB or C/C++), but it supports these three types
of projects as standard:
Plug-in Development—Provides an environment for creating your own plugins for Eclipse. This approach is great if you want to extend Eclipse to do
new and wonderful things—but we’ll get to that later. For now, you’ll use
Eclipse just the way it is.
Simple—Provides a generic environment, which you might use for documentation.
Java—Obviously, the choice for developing a Java program. Choosing this
type of project sets up an environment with various Java-specific settings,
including a classpath, source directories, and output directories.
To create a new Java project, follow these steps:
Right-click in the Navigator view to bring up a context menu and select
In the New Project dialog box, Eclipse presents the project options: Java,
Plug-in Development, and Simple. Because you want to create a Java
program, select Java on the left side of the dialog box.
Select Java Project on the right. If you’ve installed other types of Java development plug-ins, various other types of Java projects may potentially be
The Java quick tour
listed here (EJBs and servlets, for example). But the JDT that comes standard with Eclipse only offers support for standard Java applications, so
you must choose the Java Project option.
Click Next to start the New Java Project Wizard. (A wizard is a set of dialog
boxes that prompts you through a set of well-defined, sequential steps necessary to perform a specific task. This feature is used extensively throughout Eclipse.)
The first dialog box prompts you for a project name. This is a simple
“Hello, world” example, so enter Hello. Clicking Next would take you to
a dialog box that lets you change a number of Java build settings, but for
this example you don’t need to change anything.
Click Finish.
Eclipse notifies you that this kind of project is associated with the Java
perspective and asks whether you want to switch to the Java perspective.
Check the Don’t Show Me This Message Again box and click Yes.
The perspective changes to a Java perspective (see figure 2.2). Notice that the
view in the upper-left corner is no longer the Navigator view; it is now the Package Explorer view, and it displays the new Hello project. The Package Explorer
is similar to the Navigator, but it’s better suited for Java projects; for one thing, it
understands Java packages and displays them as a single entry, rather than as a
nested set of directories. Notice also that a new icon has appeared on the left
edge of the Workbench: a shortcut for the Java perspective.
At the bottom of the window is a Tasks view. It is useful for keeping track of
what needs to be done in a project. Tasks are added to this list automatically as
Eclipse encounters errors in your code. You can also add tasks to the Task view
by right-clicking in the Tasks view and selecting New Task from the context
menu; this is a convenient way to keep a to-do list for your project.
Finally, notice the Outline view on the right side of the screen. The content of
this view depends on the type of document selected in the editor. If it’s a Java
class, you can use the outline to browse class attributes and methods and move
easily between them. Depending on whether the Show Source of Selected Element button in the main toolbar is toggled on or off, you can view your source as
part of a file (what is sometimes referred to as a compilation unit) or as distinct
Java elements, such as methods and attributes.
Eclipse Workbench
Figure 2.2 The Java perspective includes the Package Explorer view. This perspective is better
suited for Java projects because it displays Java packages as a single entry instead of a nested set
of directories.
2.3.2 Creating a Java class
Once you’ve created a project for it to live in, you can create your first Java program. Although doing so is not necessary, it’s a good practice to organize your
Java classes into packages. We’ll put all packages in this book in the hierarchy
starting with the Java-style version of the domain name associated with this
book, org.eclipseguide (which of course is the reverse of the Internet style).
Using domain names reduces the likelihood of name collisions—that is, more
than one class with exactly the same name. You can use a registered domain
name if you have one, but if not, you can use any convenient, unique, ad hoc
name, especially for private use. Finally, add a name for this particular project:
hello. All together, the package name is org.eclipseguide.hello.
The Java quick tour
Follow these steps to create your Java program:
Right-click on the project and select New→Class to bring up the New
Java Class Wizard.
The first field, Source Folder, is by default the project’s folder—leave this
as it is.
Enter org.eclipseguide.hello in the Package field.
In the class name field, enter HelloWorld.
In the section Which Method Stubs Would You Like to Create?, check the
box for public static void main(String[] args). The completed New
Java Class dialog box is shown in figure 2.3.
Click Finish, and the New Java Class Wizard will create the appropriate
directory structure for the package (represented in the Navigator by the
entry org.eclipseguide.hello under the Hello project) and the source
file HelloWorld.java under this package name.
Figure 2.3
Creating the
HelloWorld class
using the New Java
Class Wizard
Eclipse Workbench
If you examine the workspace directory in the native filesystem, you will find that
there is not a single directory named org.eclipseguide.hello, but rather the series
of directories that Java expects. If you’ve installed Eclipse in C:\Eclipse, the full
path to your new source file will be C:\Eclipse\workspace\org\eclipseguide\hello\
HelloWorld.java. Normally, though, you only need to deal with the visual representation that Eclipse provides in the Package Explorer view.
In the editor area in the middle of the screen, you see the Java code generated by the wizard. Also notice that tabs now appear at the top of the editor area,
which allow you to select between the Welcome screen that first appeared and
this new HelloWorld.java file. (You don’t need the Welcome screen anymore, so
you can click on the Welcome tab and click the X in the tab to make it go away.)
You may also want to adjust the size of your windows and views to get a more
complete view of the source code and the other views.
The code that’s automatically generated is just a stub—the class with an
empty method. You need to add any functionality, such as printing your “Hello,
world!”. To do this, alter the code generated by Eclipse by adding a line to
main() as follows:
* Created on Feb 14, 2003
* To change this generated comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
package org.eclipseguide.hello;
* @author david
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
Code completion features
Notice that as you type the opening parenthesis, Eclipse helpfully inserts its partner, the closing parenthesis, immediately after the cursor. The same thing happens when you type the double quote to begin entering “Hello, world!”. This is
one of Eclipse’s code-completion features. You can turn off this feature if you
find it as meddlesome as a backseat driver, but like many of Eclipse’s other features, if you live with it, you may learn to love it.
The Java quick tour
Figure 2.4 The Eclipse code assist feature displays a list of proposed methods and their Javadoc
comments. Scroll or type the first letter (or more) to narrow the choice, and then press Enter to
complete the code.
Depending on how quickly you type, you may see another code-completion feature called code assist as you type System.out.println. If you pause after typing a
class name and a period, Eclipse presents you with a list of proposals—the methods and attributes available for the class, together with their Javadoc comments.
You can find the one you want by either scrolling through the list or typing the
first letter (or more) to narrow the choice; pressing Enter completes the code
(see figure 2.4). This is most useful when you can’t remember the exact name of
the method you’re looking for or need to be reminded what parameters it takes;
otherwise you’ll find that it’s usually faster to ignore the proposal and continue
typing the method name yourself.
You can also invoke code completion manually at any time by pressing CtrlSpace. The exact effect will depend on the context, and you may wish to experiment a bit with this feature to become familiar with it. It can be useful, for example, after typing the first few letters of a particularly long class name.
Eclipse’s code-generation feature is powerful and surprisingly easy to customize, because it is implemented using simple templates. You’ll see it in greater
depth when we examine Eclipse’s settings and preferences.
2.3.3 Running the Java program
You’re now ready to run this program. There are several things you might want
to consider when running a Java program, including the Java runtime it should
Eclipse Workbench
use, whether it will take any command-line parameters, and, if more than one
class has a main() method, which one to use. The standard way to start a Java
program in Eclipse is to select Run→Run from the Eclipse menu. Doing so
brings up a dialog box that lets you configure the launch options for the program; before running a program, you need to create a launch configuration or
select an existing launch configuration.
For most simple programs, you don’t need a special launch configuration, so
you can use a much easier method to start the program: First make sure the HelloWorld source is selected in the editor (its tab is highlighted in blue) and then do
the following from the Eclipse menu:
Select Run→Run As→Java Application.
Because you’ve made changes to the program, Eclipse prompts you to
save your changes before it runs the program. Click OK.
The Task view changes to a Console view and displays your program output (see figure 2.5).
You may wonder why no separate step is required to compile the .java file into a
.class file. This is the case because the Eclipse JDT includes a special incremental
compiler and evaluates your source code as you type it. Thus it can highlight
things such as syntax errors and unresolved references as you type. (Like
Eclipse’s other friendly features, this functionality can be turned off if you find it
annoying.) If compilation is successful, the compiled .class file is saved at the
same time your source file is saved.
Figure 2.5
The Eclipse Console
view displays the
output from the
HelloWorld program.
The Java quick tour
2.3.4 Debugging the Java program
If writing, compiling, and running a Java program were all Eclipse had to offer,
it probably wouldn’t seem worth the bother of setting up a project and using perspectives, with their shifting views, to get around; using a simple text editor and
compiling at the command line is at least as attractive. As you learn how to use
Eclipse more effectively, it will become increasingly obvious that Eclipse does have
much more to offer, largely because it interprets the code in a more comprehensive way than a simple editor can—even an editor that can check syntax.
Eclipse’s ability to run the code interactively is one major benefit. Using the
JDT debugger, you can execute your Java program line by line and examine the
value of variables at different points in the program, for example. This process
can be invaluable in locating problems in your code.
Before starting the debugger, you need to add a bit more code to the HelloWorld program to make it more interesting. Add a say() method and change the
code in the main() method to call say() instead of calling System.out.
println() directly, as shown here:
public class HelloWorld {
public static void main(String[] args) {
say("Hello, world!");
public static void say(String msg) {
for (int i = 0; i < 3; i++) {
To prepare for debugging, you also need to set a breakpoint in your code so the
debugger suspends execution and allows you to debug—otherwise, the program
will run to completion without letting you do any debugging. To set a breakpoint,
double-click in the gray margin on the left side of the editor, next to the call to
say(). A blue dot will appear, indicating an active breakpoint.
Starting the program under the debugger is similar to running it. Eclipse
provides two options: Use the full-service Run→Debug menu selection to use a
launch configuration, or use the express Run→Debug As→Java Application selection if the default options are OK. Here, as before, you can use the latter.
Make sure the source for HelloWorld is selected in the editor and select Run→
Debug As→Java Application from the main menu. Eclipse will start the program,
change to the Debug perspective, and suspend execution at the breakpoint (see
figure 2.6).
Eclipse Workbench
Figure 2.6 Debugging HelloWorld: Execution is suspended at the first breakpoint.
The Debug perspective includes several new views that are, not surprisingly, especially useful for debugging. First, at top left, is the Debug view (not to be confused
with the Debug perspective to which it belongs), which shows the call stack and
status of all current threads, including any threads that have already run to completion. Your program, which Eclipse started, has hit a breakpoint, and its status
is shown as Suspended.
Stepping through code
In the title bar of the Debug view is a toolbar that lets you control the program’s
execution. The first few tool buttons, which resemble the familiar controls of
electronic devices such as CD players, allow you to resume, suspend, or terminate
the program. Several buttons incorporate arrows in their design; these allow you
to step through a program a line at a time. Holding the mouse over each button
in turn will cause tool tips to appear, identifying them as Step With Filters, Step
The Java quick tour
Into, Step Over, and Step Return. (There are several other buttons that we’ll
ignore for now; we’ll look at them in chapter 3, “The Java Development Cycle:
Test, Code, Repeat,” when we examine debugging in greater detail.)
For example, click the second step button, Step Into. Doing so executes the
line of code that is currently highlighted in the editor area below the Debug view:
the call to the say() method. Step Into, as the name suggests, takes you into the
method that is called: After clicking Step Into, the highlighted line is the first
executable line in say()—the for statement.
The Step With Filters button works the same as Step Into, but it’s selective
about what methods it will step into. You normally want to step only into methods
in your own classes and not into the standard Java packages or third-party packages. You can specify which methods Step Filter will execute and return from
immediately by selecting Window→Preferences→Java→Debug→Step Filtering and
defining step filters by checking the packages and classes listed there. Taking a
moment to set these filters is well worth the trouble, because Step With Filters
saves you from getting lost deep in unknown code—something that can happen
all too often when you use Step Into.
Evaluating variables and expressions
To the right of the Debug view is a tabbed notebook containing views that let you
examine and modify variables and breakpoints. Select the Variables tab (if it isn’t
already selected). This view shows the variables in the current scope and their
values; before entering the for loop, this view includes only the say() method’s
msg parameter and its value, “Hello, world!”. Click either Step Over or Step Into
to enter the for loop. (Both have the same effect here, because you don’t call any
methods in this line of code.) The Variables view will display the loop index i
and its current value, 0.
Sometimes a program has many variables, but you’re interested in only one or
a few. To watch select variables or expressions, you can add them to the watch list
in the Expression view. To do this, select a variable—i, for instance—by doubleclicking on it in the editor, and then right-click on the selection and choose Watch
from the context menu. The variable (and its value, if it’s in scope) will appear in
the Expressions view.
One significant advantage of watching variables in the Variables and Expressions views over using print statements for debugging is that you can inspect
objects and their fields in detail and change their values—even normally immutable strings. Return to the Variables view and expand the msg variable to show its
attributes. One of these is a char array, value, which can be expanded to reveal
Eclipse Workbench
the individual characters in the msg String. For example, double-click on the
character H, and you will be prompted to enter a new value, such as J.
The Display view is in the same tabbed notebook. It allows you to enter any
variables that are in scope, or arbitrary expressions including these variables.
Select Display view and enter the following, for example:
To immediately evaluate this expression, you must first select it and then click
the second Display view tool button (Display Result of Evaluating Selected Text),
which displays the results in the Display view. It’s usually better to click the first
tool button (Inspect Result of Evaluating Selected Text), because it adds the expression to the Expressions view. Either way, the value displayed is not automatically
updated as the variables in the expression change; but in the Expressions view,
you have the option of converting the expression into a watch expression, which is
updated as you step through the code. To do this, change to the Expressions view.
Notice that the Inspect icon (a magnifying glass) appears next to the expression.
Click on the expression and select Convert to Watch Expression from the context
menu. The icon next to the expression will change to the Watch icon.
Let’s go back to stepping through the code. You previously left the cursor at
the call to System.out.println(). If you want to see the code for System.out.
println(), you can click Step Into; otherwise click Step Over to execute the System.out.println() method and start the next iteration of the for loop.
Below the editor area is another tabbed notebook, which includes a Console
view. Program output appears here; if you made the earlier change to the variable
msg, the line “Jello, world!” will appear. You can either continue to click Step Over
until the loop terminates or, if you find this process tedious, click Step Return to
immediately finish executing the say() method and return to the main() method.
Or, just click the Resume button to let the program run to the end.
2.3.5 Java scrapbook pages
When you’re writing a program, you sometimes have an idea that you’re not sure
will work and that you want to try before going through the trouble of changing
your code. Eclipse provides a simple but slick alternative to starting a new
project (or writing a small program using a simple editor for execution at a command prompt): Java scrapbook pages. By virtue of its incremental compiler, you
can enter arbitrary Java code into a scrapbook page and execute it—it doesn’t
need to be in a class or a method.
Preferences and other settings
To create a Java scrapbook page, change to the Java perspective, right-click
on the HelloWorld project, and select New→Scrapbook Page from the context
menu. When you’re prompted for a filename, enter Test. Enter some Java code,
such as the following example:
for(int i = 1; i < 10; i++)
To execute this code, you first need to import the org.eclipseguide.hello package, as follows:
Right-click inside the editor pane and select Set Imports from the context menu.
In the Java Snippet Imports dialog box that appears, select Add Packages.
In the next dialog box, type org.eclipseguide.hello in the Select the Packages to Add as Imports field. (You don’t have to type the complete
name—after you’ve typed one or more letters you can choose it from the
list that Eclipse presents.)
Click OK.
Now you can execute the previous code snippet:
Highlight the code by clicking and dragging with the mouse.
Right-click on the selected code and select Execute from the context menu.
As with a regular Java program, the output from this code snippet appears
in the console view below the editor.
This code doesn’t require any additional imports; but if you used StringTokenizer, for example, you could import the appropriate package (java.util.*) as
described. In such a case, however, it’s easier to import the specific type by selecting Add Types in the Java Snippet Imports dialog box and typing in StringTokenizer. Eclipse will find the appropriate package and generate the fully qualified
type name for you.
2.4 Preferences and other settings
So far, you’ve been using Eclipse with all its default settings. You can change
many things to suit your taste, your working style, or your organization’s coding
conventions, by selecting Window→Preferences. Using the dialog that appears,
Eclipse Workbench
you can change (among numerous other settings) the fonts displayed, whether
tabs appear at the top or bottom of views, and the code formatting style; you can
also add classpath entries and new templates for generating code or comments.
In this section, we’ll look at a few of the settings you might want to change.
2.4.1 Javadoc comments
First, let’s edit the text that appears when you create a new class. You’ll remove
the placeholder text, To change this generated comment…, and expand the Javadoc
comments a bit. You’ll also provide a reminder that you need to type in a class
summary and a description. Follow these steps:
Select Window→Preferences→Java→Code Generation.
Click the Code and Comments tab on this page.
Select Code→New Java files, and click the Edit button.
Change the text to the following:
/* ${file_name}
* Created on ${date}
Click OK in the Edit Template dialog box.
In addition to changing the template used whenever a new Java file is created,
you need to change one of the templates it includes: the typecomment template.
This is found on the same page, Code and Comments, under Comments:
Select Comment→Types and click the Edit button.
Change the text to the following:
* Add one sentence class summary here.
* Add class description here.
* @author ${user}
* @version 1.0, ${date}
Notice that when you edit the template text, you don’t need to type ${date}—
you can select it from the list of available variables by clicking the Insert Variable
button. Appropriate values for the two variables in this template (${user} and
${date}) will be inserted when the code is generated.
Preferences and other settings
To see your changes, create a new class called Test in the org.eclipseguide.
hello package. Note how all the variables have been filled out.
2.4.2 Format style
Two general styles are used to format Java code. The most common places an
opening brace at the end of the statement that requires it and the closing brace
in the same column as the statement, like this:
for(i = 0; i < 100; i++) {
// do something
This is the default style that Eclipse uses when you right-click on your source code
and select Format from the context menu.
The other style places the opening and closing braces in the same column as
the statement. For example:
for(i = 0; i < 100; i++)
// do something
To change to this style, do the following:
Select Java→Code Formatter in the Preferences dialog.
In the Options area, select the first tab, New Lines.
Check the first selection, Insert a New Line Before an Opening Brace.
When you click to enable this option, the sample code shown in the window below the options is updated to reflect your selection. You may want
to experiment with some of the other options to see their effects.
One of this book’s authors prefers to enable Insert New Lines in Control Statements and Insert a New Line in an Empty Block, because he finds that doing so
makes the structure of the code more obvious. But the important point (beyond
one author’s personal preference) is that the Eclipse Java editor makes it easy to
change styles and reformat your code. If you are working as part of a team with
established conventions and your personal preference doesn’t conform, this feature lets you work in the style of your choice and reformat according to the coding convention before checking in your code.
2.4.3 Code generation templates
You saw earlier that when editing source code in the Java editor, pressing CtrlSpace invokes Eclipse’s code-generation feature. Depending on the context, this
Eclipse Workbench
key combination causes a template to be evaluated and inserted into the source
code at that point.
You’ve already seen one example of a template: the code-generation template
the New Class Wizard uses to add comments when it creates a new class file. In
addition to this and the other code- and comment-generation templates, another
set of templates is used to create boilerplate code such as flow control constructs;
these templates are found in preferences under Java→Editor→Templates.
Let’s create a template to simplify typing System.out.println():
Select Windows→Preferences→Java→Editor→Templates.
Click the New button.
In the New Template dialog that appears, enter sop as the name, ensure
that the context is Java, and enter Shortcut for System.out.println() as
the description.
Enter the following pattern for the template:
Click OK in the New Template dialog box (see figure 2.7).
Click OK in the Preference dialog to return to the Workbench.
The ${cursor} variable here indicates where the cursor will be placed after the
template is evaluated and inserted into the text.
To use the new template in the Java editor, type sop and press Ctrl-Space (or
type s, press Ctrl-Space, select sop from the list that appears, and press Enter).
Figure 2.7 Creating a shortcut for System.out.println() using a Java editor template
Preferences and other settings
The letters sop are replaced with the System.out.println() method call, and the
cursor is replaced between the quotation marks, ready for you to type the text to
be printed.
Let’s create one more template to produce a for loop. There are already three
for loop templates; but the template you’ll create is simpler than the existing
ones, which are designed to iterate over an array or collection:
Select Windows→Preferences→Java→Editor→Templates.
Click the New button.
Enter for as the name, Simple for loop as the description, and the following pattern:
for(int ${index}=0; ${index}< ${cursor}; ${index}++})
Click OK in the New Template dialog box.
Click OK in the Preference dialog to return to the Workbench.
Notice that this example uses a new variable, ${index}, which proposes a new
index to the user. By default, this index is initially i; but the cursor is placed on
this index, and anything you type (such as j or foo) replaces the ${index} variable everywhere in the template.
Try this new template by typing for and pressing Ctrl-Space. From the list
that appears, select the entry Simple For Loop. Type a new name for the index
variable, such as loopvar, and notice that it automatically appears in the test and
increment clauses. You might also notice that the index variable has a green underline, indicating a link; pressing Tab will advance the cursor to the next link. In
this case, pressing Tab takes you to the ${cursor} variable. At this point, you can
type a constant, variable, or other expression, as appropriate.
2.4.4 Classpaths and classpath variables
There are several ways you can add a directory or a JAR file to a project’s classpath: when you create the class using the New Class Wizard, by editing your
project options, or by creating a launch configuration for your project. In each
case, you can either enter the path to the JAR file or directory you wish to add, or
you can use a classpath variable. If you are only adding a JAR file for testing purposes, or if the JAR file is one you’ll use only in this project, it’s easiest to add the
path and filename explicitly. But if it’s something you are likely to use in many of
your projects (for example, a JDBC driver), you may wish to create a classpath
Eclipse Workbench
variable. Besides being easier to type, a classpath variable provides a single location to specify the JAR files used by your projects. This makes it easier to manage
your JAR files. When you want to upgrade to a new version of a JAR, a single
change will update all your projects.
Suppose you will be using the MySQL database and that the full path and filename of your JDBC driver is c:\mysql\jdbc\lib\mm.mysql-2.0.14-bin.jar. To create
a classpath variable for this JAR file, open the Window→Preferences dialog and
select Java→Classpath Variables. Click New and enter MYSQL_JDBC as the
name; either browse for the JAR file by clicking the File button or type the path
and filename manually. Click OK twice to save and return to the Workbench.
Now, when you need to add the MySQL JDBC JAR to a project, you don’t have
to search your hard drive for it; MYSQL_JDBC is one of the available classpath variables you can select. To add it to your Hello project, for example, right-click on
the project name and select Properties from the context menu. Select Java Build
Path on the left side of the dialog box that appears and then select the Libraries
tab on the right. You could add the JAR explicitly by selecting Add External Jars,
but instead select Add Variable, click MYSQL_JDBC (see figure 2.8), and click OK.
Figure 2.8
Creating a new classpath variable.
Classpath variables make it easier
to manage your classpath and
provide flexibility as well.
2.4.5 Exporting and importing preferences
Eclipse’s preferences and settings are numerous, and you can spend a lot of time
customizing it to your taste and needs. Fortunately, there is a way to save these
settings so you can apply them to another Eclipse installation or share them with
your friends, or, more importantly, so you have a backup in case the file they are
stored in (the Eclipse metadata file) gets corrupted.
The Windows→Preferences box has two buttons at the bottom: Import and
Export. To save your preferences, click the Export button, type in a filename, and
click Save to create an Eclipse preference file. To restore preferences from a preference file, click the Import button, locate the file, and click Open.
2.5 Summary
Many different versions of Eclipse are available—you aren’t limited to using only
a stable, officially released version. This is one of the most interesting features of
open source software. Deciding which one to use requires balancing stability with
features. If you need a rock-solid product, you may wish to stick to a release version. If you are a little more daring or you absolutely require a specific new feature,
you may wish to try the latest stable release. If you’re just curious to see what’s
new, you can try an integration build. In this book, we’re using the official 2.1
release, but most of the material will remain largely applicable to future releases.
The first key to using Eclipse effectively is understanding its organizational
concepts of perspectives, views, and editors. The Eclipse Workbench—the window that appears on your screen when you start Eclipse—contains a number of
different panes called views. The different views that appear at one time on the
Workbench are especially selected to enable you to accomplish a specific task, such
as working with Java source files. The title bar of each view has a window menu
and, optionally, a view-specific menu, a toolbar, or both.
In addition to views, most perspectives have an editor as their central component. The specific editor that appears at any given time depends on the resource
being edited. A Java source file, for example, will be opened automatically using
the JDT Java editor. The Workbench also has a number of other UI elements
beside views and an editor: a main menu bar at the top, a main toolbar below that,
and a shortcut toolbar along the left side. Because a perspective is a collection of
these views, menus, toolbars, and their relative positions, all of these elements
can change as the perspective changes. The best way to learn how to use these
features is to perform basic tasks, beginning with creating a Java project. (Eclipse
is not limited to creating Java projects, but the Java Development Toolkit that is
included is powerful, easy to use, and the most popular reason for using Eclipse.)
Writing a program, running it, and debugging it provides a good introduction to
Eclipse’s features.
Eclipse Workbench
Eclipse is also highly customizable. You can modify many settings and preferences using the Windows→Preferences selection from the main menu. Preferences can be saved and restored using the Windows→Preferences Import and
Export buttons; if you spend a lot of time customizing Eclipse, it’s a good idea to
export your changes to an Eclipse preference file for backup.
Was this manual useful for you? yes no
Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Download PDF