
Java developers have quickly made Eclipse one of the most popular
Java coding tools on Mac OS X. But although Eclipse is a comfortable
tool to use every day once you know it, it is not easy to get started
with. An earlier ADC article, "Eclipse and
Mac OS X: A Natural Combination" provided an introduction to
Eclipse; this article goes a step further, helping you start
working on projects, get over the initial hurdles and become comfortable with Eclipse.
This article is based on three examples. The first, the classic
HelloWorld example, introduces the IDE, shows you how to create a
project, and how to create, compile, and run a class. For the second
example, we will import the base Swing application created by Xcode and
work with it in Eclipse. You will also learn how to customize the
Eclipse environment and start taking advantage of the Java-specific,
code-aware features such as code assist and refactoring. In the third
example, we will work with an example that introduces the Standard
Widget Toolkit (SWT). SWT is a GUI framework created by the Eclipse
foundation that you can use in place of Swing. This example shows you a
basic example of what settings are needed to create and run an SWT
application from within Eclipse.
Getting Started
To download Eclipse, point Safari at the Eclipse download
page. The site detects that you are using Mac OS X and
highlights the latest release at the top of the page. The current
release is Eclipse Platform 3.0.1 Mac OS X; however, as there have been
improvements to the Mac OS X version of Eclipse since this release,
you should instead download the latest milestone/stable release. You
can see a link to these files at the right side of the page as part
of the list of the top-10 Eclipse downloads. The current milestone as of this writing is
3.1M5a. Follow the link and download a file with a name something like
eclipse-SDK-3.1M5a-macosx-carbon.tar.gz. Expand this into the Eclipse
folder, look inside and double-click on the Eclipse application.
Whether you are coming to Eclipse from another IDE such as Xcode
or if you are coming from a text editor and command-line tools, you
will find there is a bit of a learning curve. The first difference
appears immediately each time you start Eclipse, when you are prompted to
choose your workspace. All projects contained in the same workspace
are visible in some views and you may find that you want to
conceptually separate projects by creating a new workspace for each
project. This is a matter of taste but is unnecessary as your project
files need not be located in the workspace. You will see an example of
this in the next section. For now, choose the default selection for
your workspace as shown in Figure 1. After working with the three
examples detailed in this article, you should have a better feel about
whether or not you prefer a single workspace or separate workspaces
for individual projects or for families of projects.
Figure 1: Selecting Your Workspace.
Create a new project by selecting File > New > Project. Follow
the wizard and select the option "Java Project" and press the Next
button. In Figure 2 you can see that you have the choice to create
the project inside the workspace or elsewhere. You can also create
the project from existing source code. For now, type in the name
HelloWorld for the project and select Finish.
Figure 2: Creating a Project.
You next are asked whether you wish to switch to the
Java perspective. Respond "Yes". This brings you to the view that you
will use for Java development. You can look ahead at Figure 6 to see
the components of the Java perspective. Create a new class using File
> New > Class or by right clicking on HelloWorld and following
the popup menu to select New > Class. You see a class creation
dialog box like that shown in Figure 3. Enter "Welcome" in the Name
field, leave the public radio button selected in the Modifiers, and
leave the value of the Superclass field
as java.lang.Object. All classes in a Java program extend
another class with the Object class at the root of the tree. As is
tradition, classes with Object as their superclass do not include
the extends keyword in the class declaration. You can
also save yourself a bit of typing by checking that you want a method
stub created for public static void main(String[]
args). The filled in form should look like this:
Figure 3: Creating a Java Class.
The following code is generated:
public class Welcome {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
To complete your HelloWorld example, replace the line
//TODO Auto-generated method stub with the
customary System.out.println("Hello, World"); To
experiment with the code assist feature, pause after
typing System. The box shown in Figure 4 appears with
suggestions for completing the code. The fourth entry
is out which is of type PrintStream. Type
the letter "o" and out is selected and a second box appears with documentation further
describing System.out. You can configure the length of the pause before the hints appear using Eclipse > Preferences.
Figure 4: Code Assistance.
Eclipse makes it easy for you to refactor your code. You may later
decide to change the name of a class, method, or variable. Eclipse helps
you by identifying all references to the name you wish to change.
Eclipse is even smart enough to realize when you have used the same name
in different contexts so that it is not just doing a global search and
replace. Renaming is one example of supported refactorings in Eclipse.
You may also wish to move a class. Notice that there is a
warning at the top of the wizard shown in Figure 3 recommending that you
not use the default package. Let's go back and create a package named
greetings and move the Welcome class into this new package. If we did
this by hand we would have to remember to change all references to
this class as well as adding a package declaration to the top of the
Welcome class. Use File > New > Package to create a new package
named greetings. Now select the Welcome.java
file. Select the move refactoring either with the menu item Refactor
> Move . . . or by right clicking on Welcome.java and selecting
Refactor > Move . . . from the context menu as shown in Figure
5.
Figure 5: Refactoring to Move Classes.
At the prompt, select the greetings package and press OK. In the
package Explorer view of the Java Perspective, the Welcome.java class
is moved under the greetings package and the default package no longer
appears as it is not needed. You will notice that the source code for
Welcome.java now begins with the declaration package
greetings; One of the strengths of Eclipse is the amount of
information that the IDE infers from the underlying structure of the
program you are writing.
What remains is to run the example. In the outline view or in the
Package Explorer view, notice the green arrow associated with the
Welcome class. Right-click on this arrow and select Run As >
Run. You should see the results in a window like that shown in Figure
6. You can also run the application by selection Run > Run and
setting variables for Main, Arguments, JRE, Classpath, Source,
Environment, and Common.
Figure 6: The Java Perspective.
At this point you should have a good feel for many of the
strengths of Eclipse. You have now downloaded and begun to configure
the IDE. You have specified your workspace, created a Java project,
and explored the Java perspective. You have created a new class and a
new package, and learned how easy it is to use the Eclipse refactoring
tools to move your class from one package to another. You have
created, compiled, and run the most basic of Java programs. Now, let's
move on to working with a Swing based program.
Working with existing code
In this section you will create the default Swing project in Xcode
and work with the generated files using Eclipse. In Xcode choose File
> New Project. When the New Project wizard appears, choose Java
Swing Application, name the project XSwing and create it in the
default location. You can now quit Xcode.
In Eclipse, create another Java project. Give it the name XSwing
and select the radio button "Create project from existing
source". Browse to the directory you just created with Xcode for the
XSwing project. The location should be something like
/Users/yourname/XSwing. You can select the highlighted Finish button
if you like, or you can further configure the project by selecting the
Next button. If you do the latter, you can see that the source code
files visible to the compiler should be AboutBox.java, PrefPane.java,
and XSwing.java. Now select Finish.
Check that the Project > Build Automatically menu item is
selected. Look back at the contents of /Users/yourname/XSwing and you
will find more than a dozen .class files have been generated. Eclipse has automatically built your saved project. Back in
the Eclipse Java perspective, click on the Problems tab in the bottom
right panel. You can see that there are fourteen warnings
generated. These all indicate that a named serializable class does
not declare a static final serialVersionUID field of type long. This
is not the sort of warning that you want to be bothered by.
Open the preference pane using Eclipse > Preferences. You can
see that Eclipse is very customizable. Look under Java > Compiler
> Errors/Warnings. As is shown in Figure 7, locate the item
Serializable class without serialVersionUID and change the selection
from Warning to Ignore. When you press OK you are prompted that
because the compiler settings were changed, a full rebuild is
required. Answer that yes you would like to do the full build now. All
of the warnings now disappear.
Figure 7: Customizing the Errors.
There are three classes in the XSwing project but only XSwing.java
contains a main() method. Right-click on the class
XSwing in either the Package Explorer or in the Outline view next to
the green arrow. Select Run As > Run and you are taken to the
run dialog. You can also bring up the run dialog using the menu item
Run > Run or by using the toolbar. Fortunately the keyboard
shortcut Shift-Command-F11 allows you to repeat a run as often as you
would like.
From the run dialog, click New. XSwing appears under Java
applications. Before running the application, click on the Arguments
tab and add the VM
argument -Dapple.laf.useScreenMenuBar=true. This is added
for you in Xcode by default. In Eclipse, you need to manually add this
option yourself so that the menu bar appears at the top of the screen
and not as part of the JFrame. In the next section you will see that
this step is not needed if you are using SWT instead of Swing. Figure
8 shows the result of clicking the Run button.
Figure 8: The Sample Swing Application.
Now that the application is running, let's look at some more of
Eclipse's features for working with the source code. You can reopen
the preferences panel and customize the look and feel of the code with
Java > Code Style > Formatter. Change where the opening brace
appears for methods and classes, adjust the spacing at the beginning
of lines or within methods and control statements. You have control of
scores of variables that help you display the code the way you are
most comfortable.
Once you have the editor configured the way you want, take a hard
look at the code and look for places you may want to make some
changes. The automatic refactorings give you a great deal of power and
flexibility. For example, consider the addMenus()
method.
public void addMenus() {
// (1)
fileMenu = new JMenu(resbundle.getString("fileMenu"));
fileMenu.add(new JMenuItem(newAction));
fileMenu.add(new JMenuItem(openAction));
fileMenu.add(new JMenuItem(closeAction));
fileMenu.add(new JMenuItem(saveAction));
fileMenu.add(new JMenuItem(saveAsAction));
// (2)
mainMenuBar.add(fileMenu);
editMenu = new JMenu(resbundle.getString("editMenu"));
editMenu.add(new JMenuItem(undoAction));
editMenu.addSeparator();
editMenu.add(new JMenuItem(cutAction));
editMenu.add(new JMenuItem(copyAction));
editMenu.add(new JMenuItem(pasteAction));
editMenu.add(new JMenuItem(clearAction));
editMenu.addSeparator();
editMenu.add(new JMenuItem(selectAllAction));
mainMenuBar.add(editMenu);
setJMenuBar (mainMenuBar);
}
Select the lines between comment (1) and comment (2). Right-click
on these highlighted lines and select Refactor > Extract
Method. The dialog box shown in Figure 9 appears. Fill in the method
name createFileMenu and press OK.
Figure 9: Extracting Code into a Method.
The highlighted lines are replaced with a call to the newly created
method createFileMenu() and the highlighted lines make
up the body of this new method. Eclipse does prompt you if you need to
pass information in the form of a method parameter or return type. In
this case that was not necessary so createFileMenu()
takes no arguments and has return type void. Repeat this
process to form a new method named createEditMenu(). Now
the addMenus() method looks like this:
public void addMenus() {
createFileMenu();
mainMenuBar.add(fileMenu);
createEditMenu();
mainMenuBar.add(editMenu);
setJMenuBar (mainMenuBar);
}
Notice that addMenus() almost reads like a bulleted
list of the steps you might take to add the menus. If you need to know
how you created the file menu, you know where to look. For now you
want to hide these details. Click on the triangles that appear in the
left margin next to the newly created createFileMenu()
and createEditMenu() methods. This use of code folding
makes it easy to navigate code. Most of the time that you are dealing
with the XSwing class you will have no need of looking into
the createFileMenu() method so go ahead and collapse
it. Figure 10. shows a portion of XSwing.java. The inner class
newActionClass is collapsed by default. Note the green triangle
on the left at the beginning of the paint() method. This
indicates that paint() overrides a method in a super
class.
Figure 10: Collapsing code.
You have now seen how Eclipse supports working with existing
code. You can easily add a project to your workspace even if the code
is located somewhere else. You learned how to customize Eclipse to
support the code style and level of error checking with which you are
comfortable. You collapsed portions of the code to make the source
more readable. Most importantly, you took advantage of Eclipse's
awareness of the code structure to extract lines of code into a newly
created method.
A Slightly Different Look
In this third example, you will get an SWT application up and
running. SWT, the Standard Widget Toolkit, is provided by the Eclipse
project as an alternative GUI framework to Swing or AWT. You can
develop SWT applications using a text editor and command line tools or
with another IDE. This would require a separate download of the SWT
jar files and jnilib files. Until recently, configuring Eclipse on
Mac OS X to run an SWT application during development was tricky. Now,
as you will soon see, it is quite easy to compile and run an SWT
application with Eclipse.
In Eclipse, create a new Java Project and name it XSWT. Right-click
on XSWT in the Package Explorer view and select Java Build Path shown below in Figure 11. You
need to add the SWT jar files to this project. You find these in
the Eclipse distribution's plugins folder in the
eclipse/plugins/org.eclipse.swt.carbon_3.1.0/ws/carbon directory. Select the
Libraries tab and click the Add External JARs button. Navigate to this
directory and select both the swt.jar and swt-pi.jar files. Press Open. These files
now appear in the Libraries tab so you can press OK.
Figure 11: Adding the SWT .jar Files.
Running an SWT application in Eclipse on Mac OS X has gotten much
easier recently. Older tutorials direct you to further
configure Eclipse to find the corresponding native files in the
/eclipse/plugins/org.eclipse.swt.carbon_3.1.0/os/macosx/ppc
directory. This is no longer necessary. Eclipse can now find the files
libswt-carbon-3132.jnilib, libswt-pi-carbon-3123.jnilib, and
libswt-webkit-carbon-3123.jnilib without further information. Note
that the number 3132 in the file names will change for each
release.
The SWT requires that you learn a new API. Eclipse helps with code
assist, but you still need to pick up a book that gives you a high
level look at the libraries. For example, working with SWT's Menus and
MenuItems differs in significant ways from working with Swing's JMenus
and JMenuItems. Here is the core of what the code in this example will do:
setUpDisplay();
createLabel();
createMenuBar();
revealDisplay();
Although there is not a direct mapping from familiar Swing components to SWT
components, you should be able to read and understand the basic GUI code. Create a class called SWTGreeter with the following code:
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
public class SWTGreeter {
private Display display;
private Shell shell;
SWTGreeter() {
setUpDisplay();
createLabel();
createMenuBar();
revealDisplay();
}
private void setUpDisplay() {
display = new Display();
shell = new Shell(display);
shell.setSize(200, 100);
shell.setText("SWTGreeter");
}
private void createMenuBar() {
Menu menu = new Menu(shell, SWT.BAR);
shell.setMenuBar(menu);
MenuItem fileMenuItem = new MenuItem(menu, SWT.CASCADE);
fileMenuItem.setText("File");
MenuItem editMenuItem = new MenuItem(menu, SWT.CASCADE);
editMenuItem.setText("Edit");
}
private void createLabel() {
Label label = new Label(shell, SWT.CENTER);
label.setText("Hello SWT");
label.setBounds(shell.getClientArea());
}
private void revealDisplay() {
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public static void main(String[] args) {
new SWTGreeter();
}
}
The File and Edit menus do not contain any menu items, but this is
enough code to display the first two drop down menus in the
menubar. Run this as an SWT Application by right-clicking on
SWTGreeter in the Package Explorer and select Run As >
SWTApplication. The result should look like Figure 12.
Figure 12: The SWT Application.
Notice that the File and Edit menus appear where they belong, in
the screen menu bar, without requiring any specific parameters be
set. There is a lot more work that needs to be done to create a fully
functioning SWT application that looks and feels like a native Mac
application but this simple HelloWorld level example is a great place to start.
Summary
If you are doing Java development on Mac OS X, Eclipse is a
quickly evolving open source IDE which already has a rich set of tools
designed to help you. You may find yourself scratching your head the
first time you need to accomplish a new task. How do you add a jar
file? How do you make that warning go away? How do you run this
application? As you use Eclipse for your daily coding you will wonder
how you ever did without the code completion, automatic refactorings,
and other code aware features.
For More Information
Updated: 2005-02-28
|