Posted By

laurenceosx on 08/19/10


Tagged

groovy


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

laurenceosx


Groovy Swing Explorer File Drop Handler


 / Published in: Groovy
 

URL: http://java.itags.org/java-core-gui-apis/33457/

  1. import java.awt.datatransfer.*;
  2. import java.awt.dnd.*;
  3.  
  4. public class TFileDropHandler
  5. {
  6. // TFileDropHandler.groovy
  7. // Laurence Toenjes - 2010-08-18
  8. // Based on 1999 example from Cay Horstmann found at
  9. // http://java.itags.org/java-core-gui-apis/33457/
  10.  
  11. // dropped files closure example: { files -> println files };
  12. def TFileDropHandler( aSwingControl, Closure a_onDroppedFiles )
  13. { // ctor
  14. def dropTarget = new DropTarget( aSwingControl, new TFileDropTargetListener( a_onDroppedFiles ) )
  15. aSwingControl.setDropTarget( dropTarget )
  16. }
  17.  
  18. // --------------------------------------------------------
  19. class TFileDropTargetListener implements DropTargetListener
  20. {
  21. def Closure onDroppedFiles = null // our callback event
  22. public TFileDropTargetListener( a_onDroppedFiles ) { // ctor
  23. onDroppedFiles = a_onDroppedFiles }
  24.  
  25. public void dragEnter(DropTargetDragEvent event) {}
  26. public void dragExit(DropTargetEvent event) {}
  27. public void dropActionChanged(DropTargetDragEvent event) {}
  28. public void dragOver(DropTargetDragEvent event) {
  29. // provide visual feedback
  30. event.acceptDrag(DnDConstants.ACTION_COPY);
  31. }
  32.  
  33. if ( (event.getSourceActions() & DnDConstants.ACTION_COPY) != 0 ) {
  34. event.acceptDrop(DnDConstants.ACTION_COPY);
  35. }
  36. else {
  37. event.rejectDrop();
  38. return; // !!!!!!!!!!!!!!!!!!!!!
  39. }
  40. Transferable transferable = event.getTransferable();
  41. DataFlavor[] flavors = event.getCurrentDataFlavors();
  42. for (int i = 0; i < flavors.length; i++) {
  43. DataFlavor dataFlavor = flavors[i];
  44. try {
  45. // file flavor
  46. if ( dataFlavor.equals( DataFlavor.javaFileListFlavor ) ) {
  47. java.util.List fileList = (java.util.List) transferable.getTransferData(dataFlavor);
  48. def files = []
  49. fileList.each { files << it }
  50. this?.onDroppedFiles( files )
  51. event.dropComplete(true);
  52. }
  53. }
  54. event.dropComplete(false);
  55. }
  56. } // end for
  57. event.dropComplete(false);
  58. } // end drop
  59. }
  60. // --------------------------------------------------------
  61.  
  62. public static void main(String[] args) {
  63. // simple example
  64. def f = new javax.swing.JFrame()
  65. f.setDefaultCloseOperation( javax.swing.JFrame.EXIT_ON_CLOSE )
  66. f.size = [400,300]
  67. def ta = new javax.swing.JTextArea()
  68. f.add( ta )
  69.  
  70. new TFileDropHandler( ta, { files ->
  71. files.each {
  72. ta.append("${it}\n")
  73. }
  74. } )
  75.  
  76. f.show()
  77. }
  78. }

Report this snippet  

You need to login to post a comment.