Debian Codegraph @

src/dr/app/gui/FileDrop.java

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