I have created a Swing application and I'm trying to configure Drag and Drop support for a JTextArea. There are two capabilities I need for this object, I want it to accept text pasted into it from the clipboard and I also want to accept files dropped onto the object, grab the file name and then send that to another routine which will open the file, read the contents, and perform some work.
However, I cannot even get past first base on this. I have created a class of transferhandler as follows:
class FileDropHandler extends TransferHandler { public boolean canImport(TransferSupport supp) { /* for the demo, we'll only support drops (not clipboard paste) */ System.out.println("We are in FileDropHandler"); // ConsoleOutput("this is a test"); if (!supp.isDrop()) { return false; } /* return true if and only if the drop contains a list of files */ return supp.isDataFlavorSupported(DataFlavor.javaFileListFlavor); } public boolean importData(TransferSupport supp) { System.out.println("We are in FileDropHandler"); if (!canImport(supp)) { return false; } /* fetch the Transferable */ Transferable t = supp.getTransferable(); try { /* fetch the data from the Transferable */ Object data = t.getTransferData(DataFlavor.javaFileListFlavor); /* data of type javaFileListFlavor is a list of files */ java.util.List fileList = (java.util.List)data; System.out.println("Filelist " + fileList.size()); /* loop through the files in the file list */ // for (File file : fileList) { /* This is where you place your code for opening the * document represented by the "file" variable. * For example: * - create a new internal frame with a text area to * represent the document * - use a BufferedReader to read lines of the document * and append to the text area * - add the internal frame to the desktop pane, * set its bounds and make it visible */ // } } catch (UnsupportedFlavorException e) { return false; } catch (IOException e) { return false; } return true; } }
I have created an object using that class as the type and have set the JTextArea to use that transferhandler:
txtString.setDropMode(DropMode.USE_SELECTION); txtString.setTransferHandler(MyTransferHandler);
Now....if I comment out the second line above so the JTextArea uses the default transferhandler the JTextArea will accept drag and drop and the file name will appear in the JTextArea - which is not what I want.
When I set the object to use MyTransferHandler it rejects all drag and drops.
Please note that within the new class I have Println commands which I thought would send messages out to the console when that piece of code was executed - but nothing ever appears on the console which indicates to me the code is not being executed????
Please help, I have spent hours on this and don't know what to try next!