Creating an Eclipse Project

If you've installed Eclipse and have got it running, you have access to the Ant/Eclipse interface and no extra work is needed. Development work in Eclipse is based on projects, and I'll create a new project to show how to use Ant inside Eclipse. To create a new project, select File→ New→ Project, opening the New Project dialog. Select the Java Project item and click Next.

On the next page, give this project the name AntExample. Leave the other defaults as they are and click Finish.

This opens the new project in Eclipse; you can see the AntExample project at left in Eclipse's Package Explorer.

This project is empty so far; to add Java code, select the AntExample project in the Package Explorer and select File→ New→ Class, opening the New Java Class dialog. Give the package name as org.antbook, the name of the new class as AntClass, and select the checkbox marked publicstaticvoidmain(String[]args) to make Eclipse create a main method. Click the Finish button.

This creates the code, AntClass.java, you see in the Eclipse editor at the center of Figure 11-2, complete with a main( ) method.

Click the Save icon in the toolbar to save the changes to AntClass.java, and select Run→ Run As→ Java Application. You'll see the output of this code, No worries., in the Console tab at the bottom of Eclipse.

Writing an Ant Build File in Eclipse

To create an Ant build file in Eclipse, right-click the AntExample project in the Package Explorer and select New→ File. In the File Name box, enter build.xml, and click Finish, adding this new file to the AntExample project. To JAR the output of this project, enter this XML in the build file:

After entering this XML, save the new build file. The Eclipse support for Ant is evident; build.xml appears in the Package Explorer at left with an Ant icon and the syntax in the build file is colored with XML declarations in one color, attribute values in another, and Ant keywords in another, as shown (in glorious black and white) in Figure 11-3. The targets of this build file appear at right, in the Outline view.

Figure 11-3. An Ant build file in Eclipse

TIP: If you close build.xml, you can open it again in the Eclipse Ant editor; double-click it in the Package Explorer. This is different than previous versions of Eclipse, which had no default Ant editor. You had to take extra steps to open Ant build files for editing.