source: josm/trunk/src/org/openstreetmap/josm/gui/FileDrop.java@ 2474

Last change on this file since 2474 was 2047, checked in by Gubaer, 15 years ago

fixed #3324: Loading a File -> status message

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