Open File Action
Let's create a simple NetBeans Platform application for opening files. We assume we need an "Open File" action, rather than using the Favorites window to open files, which would work just as well, if not better.
- Use the NetBeans Platform Application template in the New Project dialog to create a skeleton NetBeans Platform application.
- Add a new module and set dependencies on Datasystems API, File System API, Lookup API, Nodes API, UI Utilities API, and Utilities API.
- In the new module, define the class below:
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.cookies.OpenCookie; import org.openide.filesystems.FileChooserBuilder; import org.openide.filesystems.FileUtil; import org.openide.loaders.DataObject; import org.openide.loaders.DataObjectNotFoundException; import org.openide.util.Exceptions; import org.openide.util.NbBundle.Messages; @ActionID(category = "File", id = "org.mycore.OpenFileAction") @ActionRegistration(displayName = "#CTL_OpenFileAction") @ActionReference(path = "Menu/File", position = 10) @Messages("CTL_OpenFileAction=Open File") public final class OpenFileAction implements ActionListener { @Override public void actionPerformed(ActionEvent e) { //The default dir to use if no value is stored File home = new File(System.getProperty("user.home")); //Now build a file chooser and invoke the dialog in one line of code //"user-dir" is our unique key File toAdd = new FileChooserBuilder("user-dir").setTitle("Open File"). setDefaultWorkingDirectory(home).setApproveText("Open").showOpenDialog(); //Result will be null if the user clicked cancel or closed the dialog w/o OK if (toAdd != null) { try { DataObject.find(FileUtil.toFileObject(toAdd)). getLookup().lookup(OpenCookie.class).open(); } catch (DataObjectNotFoundException ex) { Exceptions.printStackTrace(ex); } } } } - Add the "image" module, which is in the "ide" cluster, in the Libraries tab of the application's Project Properties dialog.
Run the application. Choose File | Open File and then browse on disk to the files of your choice. Depending on whether you have support for the related file type, e.g., you're able to open image files because of the "image" module added above, the file will open in the application's editor mode.

