X

Geertjan's Blog

  • July 22, 2012

org.netbeans.spi.project.ui.ProjectOpenedHook

Geertjan Wielenga
Product Manager

If you want something to happen when a project conforming to your project type opens or closes, put an instance of org.netbeans.spi.project.ui.ProjectOpenedHook into your project type's lookup. The methods "projectOpened" and "projectClosed" are called when a project of your type opens or closes in your application's GUI.

However, let's make it more interesting! Let's say you want to integrate a tool into NetBeans IDE, for example, that will process ANY project as soon as it is opened. For that purpose, you're able to add objects into the lookup of project types over which you have no control.

Here's an example. Whenever any NetBeans project opens, a balloon message is created, i.e., shown in the bottom right of the IDE, with the possibility to search Google for information relating to the project.

The code, but note that below the ProjectOpenedHook is added to the lookup of four NetBeans projects, though it could be added to many others too, for each the annotation needs to include the related project ID:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.net.URLEncoder;
import org.netbeans.api.project.Project;
import org.netbeans.spi.project.LookupProvider;
import org.netbeans.spi.project.ui.ProjectOpenedHook;
import org.openide.awt.HtmlBrowser.URLDisplayer;
import org.openide.awt.NotificationDisplayer;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.lookup.Lookups;
@LookupProvider.Registration(projectType = {
"org-netbeans-modules-web-project",
"org-netbeans-modules-java-j2seproject",
"org-netbeans-modules-apisupport-project",
"org-netbeans-modules-apisupport-project-suite"
})
public class DefaultProjectOpenedHook implements LookupProvider {
@Override
public Lookup createAdditionalLookup(final Lookup lookup) {
Project p = lookup.lookup(Project.class);
final String name = p.getProjectDirectory().getName();
return Lookups.fixed(new ProjectOpenedHook() {
@Override
protected void projectOpened() {
NotificationDisplayer.getDefault().notify(
//display name:
"Opened " + name,
//icon:
ImageUtilities.loadImageIcon("org/netbeans.png", false),
//description:
"Search Google for " + name + "!",
//action listener:
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
String searchText = URLEncoder.encode(name, "UTF-8");
URLDisplayer.getDefault().showURL(
new URL("http://www.google.com/search?hl=en&q="
+ searchText + "&btnG=Google+Search"));
} catch (Exception eee) {
return;//nothing much to do
}
}
});
}
@Override
protected void projectClosed() {
}
});
}
}

Join the discussion

Comments ( 1 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.Captcha