source: extensions/jiwigo/trunk/src/main/java/fr/mael/jiwigo/transverse/util/filedrop/FileDrop.java @ 6821

Last change on this file since 6821 was 6821, checked in by mlg, 14 years ago

Premier commit. Actuellement, l'application gère :
-Listing des catégories
-Affichage des miniatures
-Ajout de commentaires
-gestion d'un cache pour ne pas télécharger les images plusieurs fois
-gestion d'un zoom dans le navigateur d'images
-navigateur d'images complètement refait, je viens de tester sur un grand écran, à priori, c'est beaucoup mieux
-meilleure gestion des exceptions, avec affichage de messages d'erreurs
-ajout d'un "logger" qui enregistre toutes les exceptions dans un fichier de log
-possibilité de ne pas mettre le "http://" dans l'écran de connexion
-gestion de transformations d'images dans le navigateur d'images : "flip" horizontal et vertical, rotations
-menu dans le navigateur d'images, qui permet d'effectuer toutes les actions, avec en plus, la possibilité d'imprimer une image

en cours d'implémentation : gestion des préférences de l'utilisateur. Actuellement, le fichier xml permettant d'écrire les préférences est géré,
il reste à faire un écran de gestion des préférences, avec un maximum d'options, afin que l'appli soit configurable.

File size: 29.1 KB
Line 
1package fr.mael.jiwigo.transverse.util.filedrop;
2
3import java.awt.datatransfer.DataFlavor;
4import java.io.BufferedReader;
5import java.io.File;
6import java.io.IOException;
7import java.io.PrintStream;
8import java.io.Reader;
9
10import net.iharder.dnd.FileDropListener;
11
12/**
13 * This class makes it easy to drag and drop files from the operating
14 * system to a Java program. Any <tt>java.awt.Component</tt> can be
15 * dropped onto, but only <tt>javax.swing.JComponent</tt>s will indicate
16 * the drop event with a changed border.
17 * <p/>
18 * To use this class, construct a new <tt>FileDrop</tt> by passing
19 * it the target component and a <tt>Listener</tt> to receive notification
20 * when file(s) have been dropped. Here is an example:
21 * <p/>
22 * <code><pre>
23 *      JPanel myPanel = new JPanel();
24 *      new FileDrop( myPanel, new FileDrop.Listener()
25 *      {   public void filesDropped( java.io.File[] files )
26 *          {   
27 *              // handle file drop
28 *              ...
29 *          }   // end filesDropped
30 *      }); // end FileDrop.Listener
31 * </pre></code>
32 * <p/>
33 * You can specify the border that will appear when files are being dragged by
34 * calling the constructor with a <tt>javax.swing.border.Border</tt>. Only
35 * <tt>JComponent</tt>s will show any indication with a border.
36 * <p/>
37 * You can turn on some debugging features by passing a <tt>PrintStream</tt>
38 * object (such as <tt>System.out</tt>) into the full constructor. A <tt>null</tt>
39 * value will result in no extra debugging information being output.
40 * <p/>
41 *
42 * <p>I'm releasing this code into the Public Domain. Enjoy.
43 * </p>
44 * <p><em>Original author: Robert Harder, rharder@usa.net</em></p>
45 * <p>2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.</p>
46 *
47 * @author  Robert Harder
48 * @author  rharder@users.sf.net
49 * @version 1.0.1
50 */
51public class FileDrop {
52    private transient javax.swing.border.Border normalBorder;
53    private transient java.awt.dnd.DropTargetListener dropListener;
54
55    /** Discover if the running JVM is modern enough to have drag and drop. */
56    private static Boolean supportsDnD;
57
58    // Default border color
59    private static java.awt.Color defaultBorderColor = new java.awt.Color(0f, 0f, 1f, 0.25f);
60
61    /**
62     * Constructs a {@link FileDrop} with a default light-blue border
63     * and, if <var>c</var> is a {@link java.awt.Container}, recursively
64     * sets all elements contained within as drop targets, though only
65     * the top level container will change borders.
66     *
67     * @param c Component on which files will be dropped.
68     * @param listener Listens for <tt>filesDropped</tt>.
69     * @since 1.0
70     */
71    public FileDrop(final java.awt.Component c, final Listener listener) {
72        this(null, // Logging stream
73                c, // Drop target
74                javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, defaultBorderColor), // Drag border
75                true, // Recursive
76                listener);
77    } // end constructor
78
79    /**
80     * Constructor with a default border and the option to recursively set drop targets.
81     * If your component is a <tt>java.awt.Container</tt>, then each of its children
82     * components will also listen for drops, though only the parent will change borders.
83     *
84     * @param c Component on which files will be dropped.
85     * @param recursive Recursively set children as drop targets.
86     * @param listener Listens for <tt>filesDropped</tt>.
87     * @since 1.0
88     */
89    public FileDrop(final java.awt.Component c, final boolean recursive, final Listener listener) {
90        this(null, // Logging stream
91                c, // Drop target
92                javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, defaultBorderColor), // Drag border
93                recursive, // Recursive
94                listener);
95    } // end constructor
96
97    /**
98     * Constructor with a default border and debugging optionally turned on.
99     * With Debugging turned on, more status messages will be displayed to
100     * <tt>out</tt>. A common way to use this constructor is with
101     * <tt>System.out</tt> or <tt>System.err</tt>. A <tt>null</tt> value for
102     * the parameter <tt>out</tt> will result in no debugging output.
103     *
104     * @param out PrintStream to record debugging info or null for no debugging.
105     * @param out
106     * @param c Component on which files will be dropped.
107     * @param listener Listens for <tt>filesDropped</tt>.
108     * @since 1.0
109     */
110    public FileDrop(final java.io.PrintStream out, final java.awt.Component c, final Listener listener) {
111        this(out, // Logging stream
112                c, // Drop target
113                javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, defaultBorderColor), false, // Recursive
114                listener);
115    } // end constructor
116
117    /**
118     * Constructor with a default border, debugging optionally turned on
119     * and the option to recursively set drop targets.
120     * If your component is a <tt>java.awt.Container</tt>, then each of its children
121     * components will also listen for drops, though only the parent will change borders.
122     * With Debugging turned on, more status messages will be displayed to
123     * <tt>out</tt>. A common way to use this constructor is with
124     * <tt>System.out</tt> or <tt>System.err</tt>. A <tt>null</tt> value for
125     * the parameter <tt>out</tt> will result in no debugging output.
126     *
127     * @param out PrintStream to record debugging info or null for no debugging.
128     * @param out
129     * @param c Component on which files will be dropped.
130     * @param recursive Recursively set children as drop targets.
131     * @param listener Listens for <tt>filesDropped</tt>.
132     * @since 1.0
133     */
134    public FileDrop(final java.io.PrintStream out, final java.awt.Component c, final boolean recursive,
135            final Listener listener) {
136        this(out, // Logging stream
137                c, // Drop target
138                javax.swing.BorderFactory.createMatteBorder(2, 2, 2, 2, defaultBorderColor), // Drag border
139                recursive, // Recursive
140                listener);
141    } // end constructor
142
143    /**
144     * Constructor with a specified border
145     *
146     * @param c Component on which files will be dropped.
147     * @param dragBorder Border to use on <tt>JComponent</tt> when dragging occurs.
148     * @param listener Listens for <tt>filesDropped</tt>.
149     * @since 1.0
150     */
151    public FileDrop(final java.awt.Component c, final javax.swing.border.Border dragBorder, final Listener listener) {
152        this(null, // Logging stream
153                c, // Drop target
154                dragBorder, // Drag border
155                false, // Recursive
156                listener);
157    } // end constructor
158
159    /**
160     * Constructor with a specified border and the option to recursively set drop targets.
161     * If your component is a <tt>java.awt.Container</tt>, then each of its children
162     * components will also listen for drops, though only the parent will change borders.
163     *
164     * @param c Component on which files will be dropped.
165     * @param dragBorder Border to use on <tt>JComponent</tt> when dragging occurs.
166     * @param recursive Recursively set children as drop targets.
167     * @param listener Listens for <tt>filesDropped</tt>.
168     * @since 1.0
169     */
170    public FileDrop(final java.awt.Component c, final javax.swing.border.Border dragBorder, final boolean recursive,
171            final Listener listener) {
172        this(null, c, dragBorder, recursive, listener);
173    } // end constructor
174
175    /**
176     * Constructor with a specified border and debugging optionally turned on.
177     * With Debugging turned on, more status messages will be displayed to
178     * <tt>out</tt>. A common way to use this constructor is with
179     * <tt>System.out</tt> or <tt>System.err</tt>. A <tt>null</tt> value for
180     * the parameter <tt>out</tt> will result in no debugging output.
181     *
182     * @param out PrintStream to record debugging info or null for no debugging.
183     * @param c Component on which files will be dropped.
184     * @param dragBorder Border to use on <tt>JComponent</tt> when dragging occurs.
185     * @param listener Listens for <tt>filesDropped</tt>.
186     * @since 1.0
187     */
188    public FileDrop(final java.io.PrintStream out, final java.awt.Component c,
189            final javax.swing.border.Border dragBorder, final Listener listener) {
190        this(out, // Logging stream
191                c, // Drop target
192                dragBorder, // Drag border
193                false, // Recursive
194                listener);
195    } // end constructor
196
197    /**
198     * Full constructor with a specified border and debugging optionally turned on.
199     * With Debugging turned on, more status messages will be displayed to
200     * <tt>out</tt>. A common way to use this constructor is with
201     * <tt>System.out</tt> or <tt>System.err</tt>. A <tt>null</tt> value for
202     * the parameter <tt>out</tt> will result in no debugging output.
203     *
204     * @param out PrintStream to record debugging info or null for no debugging.
205     * @param c Component on which files will be dropped.
206     * @param dragBorder Border to use on <tt>JComponent</tt> when dragging occurs.
207     * @param recursive Recursively set children as drop targets.
208     * @param listener Listens for <tt>filesDropped</tt>.
209     * @since 1.0
210     */
211    public FileDrop(final java.io.PrintStream out, final java.awt.Component c,
212            final javax.swing.border.Border dragBorder, final boolean recursive, final Listener listener) {
213
214        if (supportsDnD()) { // Make a drop listener
215            dropListener = new java.awt.dnd.DropTargetListener() {
216                public void dragEnter(java.awt.dnd.DropTargetDragEvent evt) {
217
218                    // Is this an acceptable drag event?
219                    if (isDragOk(out, evt)) {
220                        // If it's a Swing component, set its border
221                        if (c instanceof javax.swing.JComponent) {
222                            javax.swing.JComponent jc = (javax.swing.JComponent) c;
223                            normalBorder = jc.getBorder();
224                            jc.setBorder(dragBorder);
225                        } // end if: JComponent   
226
227                        // Acknowledge that it's okay to enter
228                        //evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
229                        evt.acceptDrag(java.awt.dnd.DnDConstants.ACTION_COPY);
230                    } // end if: drag ok
231                    else { // Reject the drag event
232                        evt.rejectDrag();
233                    } // end else: drag not ok
234                } // end dragEnter
235
236                public void dragOver(java.awt.dnd.DropTargetDragEvent evt) { // This is called continually as long as the mouse is
237                    // over the drag target.
238                } // end dragOver
239
240                public void drop(java.awt.dnd.DropTargetDropEvent evt) {
241                    try { // Get whatever was dropped
242                        java.awt.datatransfer.Transferable tr = evt.getTransferable();
243
244                        // Is it a file list?
245                        if (tr.isDataFlavorSupported(java.awt.datatransfer.DataFlavor.javaFileListFlavor)) {
246                            // Say we'll take it.
247                            //evt.acceptDrop ( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
248                            evt.acceptDrop(java.awt.dnd.DnDConstants.ACTION_COPY);
249
250                            // Get a useful list
251                            java.util.List fileList = (java.util.List) tr
252                                    .getTransferData(java.awt.datatransfer.DataFlavor.javaFileListFlavor);
253                            java.util.Iterator iterator = fileList.iterator();
254
255                            // Convert list to array
256                            java.io.File[] filesTemp = new java.io.File[fileList.size()];
257                            fileList.toArray(filesTemp);
258                            final java.io.File[] files = filesTemp;
259
260                            // Alert listener to drop.
261                            if (listener != null)
262                                listener.filesDropped(files);
263
264                            // Mark that drop is completed.
265                            evt.getDropTargetContext().dropComplete(true);
266                        } // end if: file list
267                        else // this section will check for a reader flavor.
268                        {
269                            // Thanks, Nathan!
270                            // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
271                            DataFlavor[] flavors = tr.getTransferDataFlavors();
272                            boolean handled = false;
273                            for (int zz = 0; zz < flavors.length; zz++) {
274                                if (flavors[zz].isRepresentationClassReader()) {
275                                    // Say we'll take it.
276                                    //evt.acceptDrop ( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
277                                    evt.acceptDrop(java.awt.dnd.DnDConstants.ACTION_COPY);
278
279                                    Reader reader = flavors[zz].getReaderForText(tr);
280
281                                    BufferedReader br = new BufferedReader(reader);
282
283                                    if (listener != null)
284                                        listener.filesDropped(createFileArray(br, out));
285
286                                    // Mark that drop is completed.
287                                    evt.getDropTargetContext().dropComplete(true);
288                                    handled = true;
289                                    break;
290                                }
291                            }
292                            if (!handled) {
293                                evt.rejectDrop();
294                            }
295                            // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
296                        } // end else: not a file list
297                    } // end try
298                    catch (java.io.IOException io) {
299                        io.printStackTrace(out);
300                        evt.rejectDrop();
301                    } // end catch IOException
302                    catch (java.awt.datatransfer.UnsupportedFlavorException ufe) {
303                        ufe.printStackTrace(out);
304                        evt.rejectDrop();
305                    } // end catch: UnsupportedFlavorException
306                    finally {
307                        // If it's a Swing component, reset its border
308                        if (c instanceof javax.swing.JComponent) {
309                            javax.swing.JComponent jc = (javax.swing.JComponent) c;
310                            jc.setBorder(normalBorder);
311                        } // end if: JComponent
312                    } // end finally
313                } // end drop
314
315                public void dragExit(java.awt.dnd.DropTargetEvent evt) {
316                    // If it's a Swing component, reset its border
317                    if (c instanceof javax.swing.JComponent) {
318                        javax.swing.JComponent jc = (javax.swing.JComponent) c;
319                        jc.setBorder(normalBorder);
320                    } // end if: JComponent
321                } // end dragExit
322
323                public void dropActionChanged(java.awt.dnd.DropTargetDragEvent evt) {
324                    // Is this an acceptable drag event?
325                    if (isDragOk(out, evt)) { //evt.acceptDrag( java.awt.dnd.DnDConstants.ACTION_COPY_OR_MOVE );
326                        evt.acceptDrag(java.awt.dnd.DnDConstants.ACTION_COPY);
327                    } // end if: drag ok
328                    else {
329                        evt.rejectDrag();
330                    } // end else: drag not ok
331                } // end dropActionChanged
332            }; // end DropTargetListener
333
334            // Make the component (and possibly children) drop targets
335            makeDropTarget(out, c, recursive);
336        } // end if: supports dnd
337        else {
338        } // end else: does not support DnD
339    } // end constructor
340
341    private static boolean supportsDnD() { // Static Boolean
342        if (supportsDnD == null) {
343            boolean support = false;
344            try {
345                Class arbitraryDndClass = Class.forName("java.awt.dnd.DnDConstants");
346                support = true;
347            } // end try
348            catch (Exception e) {
349                support = false;
350            } // end catch
351            supportsDnD = new Boolean(support);
352        } // end if: first time through
353        return supportsDnD.booleanValue();
354    } // end supportsDnD
355
356    // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
357    private static String ZERO_CHAR_STRING = "" + (char) 0;
358
359    private static File[] createFileArray(BufferedReader bReader, PrintStream out) {
360        try {
361            java.util.List list = new java.util.ArrayList();
362            java.lang.String line = null;
363            while ((line = bReader.readLine()) != null) {
364                try {
365                    // kde seems to append a 0 char to the end of the reader
366                    if (ZERO_CHAR_STRING.equals(line))
367                        continue;
368
369                    java.io.File file = new java.io.File(new java.net.URI(line));
370                    list.add(file);
371                } catch (Exception ex) {
372                }
373            }
374
375            return (java.io.File[]) list.toArray(new File[list.size()]);
376        } catch (IOException ex) {
377        }
378        return new File[0];
379    }
380
381    // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
382
383    private void makeDropTarget(final java.io.PrintStream out, final java.awt.Component c, boolean recursive) {
384        // Make drop target
385        final java.awt.dnd.DropTarget dt = new java.awt.dnd.DropTarget();
386        try {
387            dt.addDropTargetListener(dropListener);
388        } // end try
389        catch (java.util.TooManyListenersException e) {
390            e.printStackTrace();
391        } // end catch
392
393        // Listen for hierarchy changes and remove the drop target when the parent gets cleared out.
394        c.addHierarchyListener(new java.awt.event.HierarchyListener() {
395            public void hierarchyChanged(java.awt.event.HierarchyEvent evt) {
396                java.awt.Component parent = c.getParent();
397                if (parent == null) {
398                    c.setDropTarget(null);
399                } // end if: null parent
400                else {
401                    new java.awt.dnd.DropTarget(c, dropListener);
402                } // end else: parent not null
403            } // end hierarchyChanged
404        }); // end hierarchy listener
405        if (c.getParent() != null)
406            new java.awt.dnd.DropTarget(c, dropListener);
407
408        if (recursive && (c instanceof java.awt.Container)) {
409            // Get the container
410            java.awt.Container cont = (java.awt.Container) c;
411
412            // Get it's components
413            java.awt.Component[] comps = cont.getComponents();
414
415            // Set it's components as listeners also
416            for (int i = 0; i < comps.length; i++)
417                makeDropTarget(out, comps[i], recursive);
418        } // end if: recursively set components as listener
419    } // end dropListener
420
421    /** Determine if the dragged data is a file list. */
422    private boolean isDragOk(final java.io.PrintStream out, final java.awt.dnd.DropTargetDragEvent evt) {
423        boolean ok = false;
424
425        // Get data flavors being dragged
426        java.awt.datatransfer.DataFlavor[] flavors = evt.getCurrentDataFlavors();
427
428        // See if any of the flavors are a file list
429        int i = 0;
430        while (!ok && i < flavors.length) {
431            // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
432            // Is the flavor a file list?
433            final DataFlavor curFlavor = flavors[i];
434            if (curFlavor.equals(java.awt.datatransfer.DataFlavor.javaFileListFlavor)
435                    || curFlavor.isRepresentationClassReader()) {
436                ok = true;
437            }
438            // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
439            i++;
440        } // end while: through flavors
441
442        return ok;
443    } // end isDragOk
444
445    /**
446     * Removes the drag-and-drop hooks from the component and optionally
447     * from the all children. You should call this if you add and remove
448     * components after you've set up the drag-and-drop.
449     * This will recursively unregister all components contained within
450     * <var>c</var> if <var>c</var> is a {@link java.awt.Container}.
451     *
452     * @param c The component to unregister as a drop target
453     * @since 1.0
454     */
455    public static boolean remove(java.awt.Component c) {
456        return remove(null, c, true);
457    } // end remove
458
459    /**
460     * Removes the drag-and-drop hooks from the component and optionally
461     * from the all children. You should call this if you add and remove
462     * components after you've set up the drag-and-drop.
463     *
464     * @param out Optional {@link java.io.PrintStream} for logging drag and drop messages
465     * @param c The component to unregister
466     * @param recursive Recursively unregister components within a container
467     * @since 1.0
468     */
469    public static boolean remove(java.io.PrintStream out, java.awt.Component c, boolean recursive) { // Make sure we support dnd.
470        if (supportsDnD()) {
471            c.setDropTarget(null);
472            if (recursive && (c instanceof java.awt.Container)) {
473                java.awt.Component[] comps = ((java.awt.Container) c).getComponents();
474                for (int i = 0; i < comps.length; i++)
475                    remove(out, comps[i], recursive);
476                return true;
477            } // end if: recursive
478            else
479                return false;
480        } // end if: supports DnD
481        else
482            return false;
483    } // end remove
484
485    /* ********  I N N E R   I N T E R F A C E   L I S T E N E R  ******** */
486
487    /**
488     * Implement this inner interface to listen for when files are dropped. For example
489     * your class declaration may begin like this:
490     * <code><pre>
491     *      public class MyClass implements FileDrop.Listener
492     *      ...
493     *      public void filesDropped( java.io.File[] files )
494     *      {
495     *          ...
496     *      }   // end filesDropped
497     *      ...
498     * </pre></code>
499     *
500     * @since 1.1
501     */
502    public static interface Listener {
503
504        /**
505         * This method is called when files have been successfully dropped.
506         *
507         * @param files An array of <tt>File</tt>s that were dropped.
508         * @since 1.0
509         */
510        public abstract void filesDropped(java.io.File[] files);
511
512    } // end inner-interface Listener
513
514    /* ********  I N N E R   C L A S S  ******** */
515
516    /**
517     * This is the event that is passed to the
518     * {@link FileDropListener#filesDropped filesDropped(...)} method in
519     * your {@link FileDropListener} when files are dropped onto
520     * a registered drop target.
521     *
522     * <p>I'm releasing this code into the Public Domain. Enjoy.</p>
523     *
524     * @author  Robert Harder
525     * @author  rob@iharder.net
526     * @version 1.2
527     */
528    public static class Event extends java.util.EventObject {
529
530        private java.io.File[] files;
531
532        /**
533         * Constructs an {@link Event} with the array
534         * of files that were dropped and the
535         * {@link FileDrop} that initiated the event.
536         *
537         * @param files The array of files that were dropped
538         * @source The event source
539         * @since 1.1
540         */
541        public Event(java.io.File[] files, Object source) {
542            super(source);
543            this.files = files;
544        } // end constructor
545
546        /**
547         * Returns an array of files that were dropped on a
548         * registered drop target.
549         *
550         * @return array of files that were dropped
551         * @since 1.1
552         */
553        public java.io.File[] getFiles() {
554            return files;
555        } // end getFiles
556
557    } // end inner class Event
558
559    /* ********  I N N E R   C L A S S  ******** */
560
561    /**
562     * At last an easy way to encapsulate your custom objects for dragging and dropping
563     * in your Java programs!
564     * When you need to create a {@link java.awt.datatransfer.Transferable} object,
565     * use this class to wrap your object.
566     * For example:
567     * <pre><code>
568     *      ...
569     *      MyCoolClass myObj = new MyCoolClass();
570     *      Transferable xfer = new TransferableObject( myObj );
571     *      ...
572     * </code></pre>
573     * Or if you need to know when the data was actually dropped, like when you're
574     * moving data out of a list, say, you can use the {@link TransferableObject.Fetcher}
575     * inner class to return your object Just in Time.
576     * For example:
577     * <pre><code>
578     *      ...
579     *      final MyCoolClass myObj = new MyCoolClass();
580     *
581     *      TransferableObject.Fetcher fetcher = new TransferableObject.Fetcher()
582     *      {   public Object getObject(){ return myObj; }
583     *      }; // end fetcher
584     *
585     *      Transferable xfer = new TransferableObject( fetcher );
586     *      ...
587     * </code></pre>
588     *
589     * The {@link java.awt.datatransfer.DataFlavor} associated with
590     * {@link TransferableObject} has the representation class
591     * <tt>net.iharder.dnd.TransferableObject.class</tt> and MIME type
592     * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
593     * This data flavor is accessible via the static
594     * {@link #DATA_FLAVOR} property.
595     *
596     *
597     * <p>I'm releasing this code into the Public Domain. Enjoy.</p>
598     *
599     * @author  Robert Harder
600     * @author  rob@iharder.net
601     * @version 1.2
602     */
603    public static class TransferableObject implements java.awt.datatransfer.Transferable {
604        /**
605         * The MIME type for {@link #DATA_FLAVOR} is
606         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
607         *
608         * @since 1.1
609         */
610        public final static String MIME_TYPE = "application/x-net.iharder.dnd.TransferableObject";
611
612        /**
613         * The default {@link java.awt.datatransfer.DataFlavor} for
614         * {@link TransferableObject} has the representation class
615         * <tt>net.iharder.dnd.TransferableObject.class</tt>
616         * and the MIME type
617         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
618         *
619         * @since 1.1
620         */
621        public final static java.awt.datatransfer.DataFlavor DATA_FLAVOR = new java.awt.datatransfer.DataFlavor(
622                FileDrop.TransferableObject.class, MIME_TYPE);
623
624        private Fetcher fetcher;
625        private Object data;
626
627        private java.awt.datatransfer.DataFlavor customFlavor;
628
629        /**
630         * Creates a new {@link TransferableObject} that wraps <var>data</var>.
631         * Along with the {@link #DATA_FLAVOR} associated with this class,
632         * this creates a custom data flavor with a representation class
633         * determined from <code>data.getClass()</code> and the MIME type
634         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
635         *
636         * @param data The data to transfer
637         * @since 1.1
638         */
639        public TransferableObject(Object data) {
640            this.data = data;
641            this.customFlavor = new java.awt.datatransfer.DataFlavor(data.getClass(), MIME_TYPE);
642        } // end constructor
643
644        /**
645         * Creates a new {@link TransferableObject} that will return the
646         * object that is returned by <var>fetcher</var>.
647         * No custom data flavor is set other than the default
648         * {@link #DATA_FLAVOR}.
649         *
650         * @see Fetcher
651         * @param fetcher The {@link Fetcher} that will return the data object
652         * @since 1.1
653         */
654        public TransferableObject(Fetcher fetcher) {
655            this.fetcher = fetcher;
656        } // end constructor
657
658        /**
659         * Creates a new {@link TransferableObject} that will return the
660         * object that is returned by <var>fetcher</var>.
661         * Along with the {@link #DATA_FLAVOR} associated with this class,
662         * this creates a custom data flavor with a representation class <var>dataClass</var>
663         * and the MIME type
664         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
665         *
666         * @see Fetcher
667         * @param dataClass The {@link java.lang.Class} to use in the custom data flavor
668         * @param fetcher The {@link Fetcher} that will return the data object
669         * @since 1.1
670         */
671        public TransferableObject(Class dataClass, Fetcher fetcher) {
672            this.fetcher = fetcher;
673            this.customFlavor = new java.awt.datatransfer.DataFlavor(dataClass, MIME_TYPE);
674        } // end constructor
675
676        /**
677         * Returns the custom {@link java.awt.datatransfer.DataFlavor} associated
678         * with the encapsulated object or <tt>null</tt> if the {@link Fetcher}
679         * constructor was used without passing a {@link java.lang.Class}.
680         *
681         * @return The custom data flavor for the encapsulated object
682         * @since 1.1
683         */
684        public java.awt.datatransfer.DataFlavor getCustomDataFlavor() {
685            return customFlavor;
686        } // end getCustomDataFlavor
687
688        /* ********  T R A N S F E R A B L E   M E T H O D S  ******** */
689
690        /**
691         * Returns a two- or three-element array containing first
692         * the custom data flavor, if one was created in the constructors,
693         * second the default {@link #DATA_FLAVOR} associated with
694         * {@link TransferableObject}, and third the
695         * {@link java.awt.datatransfer.DataFlavor.stringFlavor}.
696         *
697         * @return An array of supported data flavors
698         * @since 1.1
699         */
700        public java.awt.datatransfer.DataFlavor[] getTransferDataFlavors() {
701            if (customFlavor != null)
702                return new java.awt.datatransfer.DataFlavor[] { customFlavor, DATA_FLAVOR,
703                        java.awt.datatransfer.DataFlavor.stringFlavor }; // end flavors array
704            else
705                return new java.awt.datatransfer.DataFlavor[] { DATA_FLAVOR,
706                        java.awt.datatransfer.DataFlavor.stringFlavor }; // end flavors array
707        } // end getTransferDataFlavors
708
709        /**
710         * Returns the data encapsulated in this {@link TransferableObject}.
711         * If the {@link Fetcher} constructor was used, then this is when
712         * the {@link Fetcher#getObject getObject()} method will be called.
713         * If the requested data flavor is not supported, then the
714         * {@link Fetcher#getObject getObject()} method will not be called.
715         *
716         * @param flavor The data flavor for the data to return
717         * @return The dropped data
718         * @since 1.1
719         */
720        public Object getTransferData(java.awt.datatransfer.DataFlavor flavor)
721                throws java.awt.datatransfer.UnsupportedFlavorException, java.io.IOException {
722            // Native object
723            if (flavor.equals(DATA_FLAVOR))
724                return fetcher == null ? data : fetcher.getObject();
725
726            // String
727            if (flavor.equals(java.awt.datatransfer.DataFlavor.stringFlavor))
728                return fetcher == null ? data.toString() : fetcher.getObject().toString();
729
730            // We can't do anything else
731            throw new java.awt.datatransfer.UnsupportedFlavorException(flavor);
732        } // end getTransferData
733
734        /**
735         * Returns <tt>true</tt> if <var>flavor</var> is one of the supported
736         * flavors. Flavors are supported using the <code>equals(...)</code> method.
737         *
738         * @param flavor The data flavor to check
739         * @return Whether or not the flavor is supported
740         * @since 1.1
741         */
742        public boolean isDataFlavorSupported(java.awt.datatransfer.DataFlavor flavor) {
743            // Native object
744            if (flavor.equals(DATA_FLAVOR))
745                return true;
746
747            // String
748            if (flavor.equals(java.awt.datatransfer.DataFlavor.stringFlavor))
749                return true;
750
751            // We can't do anything else
752            return false;
753        } // end isDataFlavorSupported
754
755        /* ********  I N N E R   I N T E R F A C E   F E T C H E R  ******** */
756
757        /**
758         * Instead of passing your data directly to the {@link TransferableObject}
759         * constructor, you may want to know exactly when your data was received
760         * in case you need to remove it from its source (or do anyting else to it).
761         * When the {@link #getTransferData getTransferData(...)} method is called
762         * on the {@link TransferableObject}, the {@link Fetcher}'s
763         * {@link #getObject getObject()} method will be called.
764         *
765         * @author Robert Harder
766         * @copyright 2001
767         * @version 1.1
768         * @since 1.1
769         */
770        public static interface Fetcher {
771            /**
772             * Return the object being encapsulated in the
773             * {@link TransferableObject}.
774             *
775             * @return The dropped object
776             * @since 1.1
777             */
778            public abstract Object getObject();
779        } // end inner interface Fetcher
780
781    } // end class TransferableObject
782
783} // end class FileDrop
Note: See TracBrowser for help on using the repository browser.