27.7.10

How to Programmatically Open the New File Dialog in NetBeans

The question of the day comes from Robin, who is from bstek.com in China. He sends the screenshot shown below and wonders how to enable the "New File" dialog to be opened when a button he created is clicked:

There was a discussion on the dev@openide.netbeans.org mailing list sometime ago (click here to jump into it), answering this question. And here's code that I have tried a few minutes ago (in a 6.7 build) that opens the New File dialog. However, note that the New File dialog can only open in the context of a project in NetBeans IDE. In other words, a project must be open and the assumption is that the new file will be created within that project.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import org.openide.ErrorManager;
import org.openide.cookies.InstanceCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;

public final class SomeAction implements ActionListener {

public void actionPerformed(ActionEvent e) {

Action a = findAction("Actions/Project/org-netbeans-modules-project-ui-NewFile.instance");
a.actionPerformed(e);

}

public Action findAction(String key) {
FileObject fo = FileUtil.getConfigFile(key);
if (fo != null && fo.isValid()) {
try {
DataObject dob = DataObject.find(fo);
InstanceCookie ic = dob.getLookup().lookup(InstanceCookie.class);
if (ic != null) {
Object instance = ic.instanceCreate();
if (instance instanceof Action) {
Action a = (Action) instance;
return a;
}
}
} catch (Exception e) {
ErrorManager.getDefault().notify(ErrorManager.WARNING, e);
return null;
}
}
return null;
}

}

The code above comes straight from the discussion on the mailing list. Alternative approaces are also described there. So, here's hoping this answers the question, Robin! And good luck with your plugin, looks pretty interesting so far.

May 25 2009, 06:26:38 PM PDT Permalink

3 Comments

Trackback URL: http://blogs.sun.com/geertjan/entry/how_to_programmatically_open_the


Comments:

http://blogs.sun.com/geertjan/entry/how_to_programmatically_open_the

No comments: