Brain Teaser: How Did I Do This (Part 1: The Solution)
- by Geertjan
In Part 1: The Challenge, published this time last week, I introduced a "brain teaser". The brain teaser asks you to figure out how to allow images and other files to be meaningfully dropped onto a NetBeans Platform application, i.e., on the drop something useful should happen with the dropped file: if the file is an image, the image should open in the IDE; if the file is a PDF document, the PDF viewer should open externally; if the file is a text file, it should open as a text in the IDE, etc.
Solution. And here is the solution:
http://bits.netbeans.org/dev/javadoc/org-openide-windows/org/openide/windows/ExternalDropHandler.html
When an implementation of the "ExternalDropHandler" class is available in the global Lookup, and
an object is being dragged over some part of the main window, the window system may call the methods of this class to decide whether it can
accept or reject the drag operation. And when the object is actually dropped, this class will be asked to handle the drop.
OK, so go ahead and implement the above class and put it into the Lookup.
Or... guess what? The NetBeans Platform has a default implementation of the above class, appropriately named "DefaultExternalDropHandler". Not only is this useful to learn about how to implement the ExternalDropHandler class (i.e., by reading the source here): you can simply include the module that contains this class in your own NetBeans Platform application and then your application will be able to receive external drag/drop events and do something meaningful with them thanks to the DefaultExternalDropHandler.
Do this:
Open your NetBeans Platform application in NetBeans IDE. Right-click the application in the Projects window and choose Properties.
In the Libraries tab, expand the "ide" cluster, and select "User Utilities". (That's where "DefaultExternalDropHandler.java" is found and registered in the Lookup.) Now click the "Resolve" button, if it appears, because some additional related modules need to now be included, if they haven't been included yet.
Again in the "ide" cluster in the Libraries tab, select "Image". That's the Image Editor. Click OK.
Run the application. Drag an image or some other type of file into your application, from outside the application, and you'll see the application tries to handle the drop. If the file being dragged is an image, it will open in the Image Editor, which you included in the previous step of these instructions.
Hurray, you're done. Without any programming at all, you've added a cool new feature to your application.