Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

4. Creating new Java elements via the Java model

The following will create a command which will create a new package to existing (and open) Java projects which have the same name as the Java project. For example if you have a project "de.vogella.test" in your workspace without any package this command will create the package "de.vogella.test" in this project.

Create a new plugin project "de.vogella.jdt.newelements".

Add a new command "de.vogella.jdt.newelements.AddPackage" and put it into the menu.

Create the following handler for this command.

			
package de.vogella.jdt.newelements.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;

public class AddPackage extends AbstractHandler implements IHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		IWorkspaceRoot root = workspace.getRoot();
		// Get all projects in the workspace
		IProject[] projects = root.getProjects();
		// Loop over all projects
		for (IProject project : projects) {
			try {
				// Only work on open projects with the Java nature
				if (project.isOpen()
						&& project
								.isNatureEnabled("org.eclipse.jdt.core.javanature")) {
					IJavaProject javaProject = JavaCore.create(project);
					IFolder folder = project.getFolder("src");
					// folder.create(true, true, null);
					IPackageFragmentRoot srcFolder = javaProject
							.getPackageFragmentRoot(folder);
					IPackageFragment fragment = srcFolder
							.createPackageFragment(project.getName(), true,
									null);
					System.out.println("Juhu");
				}
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}

		

Tip

This will add the package with the Java project name to all open projects in the workspace. Make you sure you really want this. You could also add the action to the context menu of the package explorer and apply it only for the selected project. You can learn how to do this in Extending the Package Explorer.

An example can be found on the source page in project "de.vogella.jdt.packageexplorer". Have a look at the command handler "AddPackage.java".