RSS

Search Engine

Thursday, July 15, 2010

Resources and Marker

4.1. Overview

Eclipse represents Resources like Projects, Files, Folders, Packages as IResource.

Marker represent additional informations for resources, e.g. an error marker. Every marker can have attributes (key / value combination). Markers can be displayed in the standard view, e.g. the Task, Bookmark or the problems view. To be displayed in these views you have to use predefined attributes.

The following will demonstrate how to create marker for a selected resource.

4.2. Create markers

Create a plug-in project "de.vogella.plugin.markers". Add the dependency to org.eclipse.core.resources", "org.eclipse.jdt.core" and "org.eclipse.jdt.ui". Create the command "de.vogella.plugin.markers.AddMarker" with the default handler "de.vogella.plugin.markers.handler.AddMarker" and add this command to the menu.

Create the following code.

    
package de.vogella.plugin.markers.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

public class AddMarker extends AbstractHandler {

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IStructuredSelection selection = (IStructuredSelection) HandlerUtil
.getActiveSite(event).getSelectionProvider().getSelection();
if (selection == null) {
return null;
}
Object firstElement = selection.getFirstElement();
if (firstElement instanceof IJavaProject) {
IJavaProject type = (IJavaProject) firstElement;
try {
IResource resource = type.getUnderlyingResource();
IMarker marker = resource.createMarker(IMarker.TASK);
marker.setAttribute(IMarker.MESSAGE, "This a a task");
marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
} catch (Exception e) {
e.printStackTrace();
}

}
return null;
}
}

If you run you can create a marker in the TODO list if you select a Java project and click your menu entry.

0 comments:

Post a Comment