Drag and Drop a file in swing applications

Hello friends,
is there anyway that i can know in my program that a file is dragged an dropped?
to be very clear, i want to allow a user to drag and drop a .txt file in my JFrame.
1. how do i know that user has dropped such file.
2. how can i restrict him to drop other files?
thanks in advance

Here is a code segment illustrating the method for obtaining the filename or path:
public void drop(final DropTargetDropEvent event)  {
          if ((event.getSourceActions() & DnDConstants.ACTION_COPY) != 0)
              event.acceptDrop(DnDConstants.ACTION_COPY);
         else {
             event.rejectDrop();
             return;
          Transferable transferable = event.getTransferable();
          DataFlavor[] flavors = event.getCurrentDataFlavors();
          for (int i = 0; i < flavors.length; i++)   {
               DataFlavor dataFlavor = flavors;
               try {
                    if (dataFlavor.equals(DataFlavor.javaFileListFlavor)) {
                         java.util.List fileList = (java.util.List) transferable.getTransferData(dataFlavor);
                         final File f = (File) fileList.get(0);
                         waiting = true;
                         Thread runner = new Thread() {
                              public void run() {                                                                  
                                   if (frame.promptToSave()) {
                                        frame.openDocument(f);     
                                   waiting = false;
                         runner.start();
                         event.dropComplete(true);
                         return;               
                    else if (dataFlavor.equals(DataFlavor.stringFlavor)) {               
                    textArea.setCaretPosition(textArea.viewToModel(event.getLocation()));
                    String s = (String) transferable.getTransferData(dataFlavor);
                    textArea.insert(s, textArea.getCaretPosition());
                    event.dropComplete(true);
                         return;          
//                    else if (d.isMimeTypeEqual("text/plain")) {               
               } catch (Exception e) {
                    event.dropComplete(false);
                    return;
          event.dropComplete(false);

Similar Messages

  • How to drag and drop a file with its Systemfile icon to a Jtext area

    I want to drag and drop a file to a JText area with its system file icon , but the problem is I cant show the file icon.
    Anyone knows this.
    this is my code.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.DnDConstants;
    import java.awt.dnd.DropTarget;
    import java.awt.dnd.DropTargetDragEvent;
    import java.awt.dnd.DropTargetDropEvent;
    import java.awt.dnd.DropTargetEvent;
    import java.awt.dnd.DropTargetListener;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    public class FileDrag extends JFrame implements DropTargetListener {
    DropTarget dt;
    File file;
    JTextArea ta;
    JLabel lbl;
    Graphics g;
    ImageIcon tmpIcon;
    public FileDrag() {
    super("Drop Test");
    setSize(300, 300);
    getContentPane().add(
    new JLabel("Drop a list from your file chooser here:"),
    BorderLayout.NORTH);
    ta = new JTextArea();
    ta.setBackground(Color.white);
    getContentPane().add(ta);
    dt = new DropTarget(ta, this);
    setVisible(true);
    public void dragEnter(DropTargetDragEvent dtde) {
    System.out.println("Drag Enter");
    public void dragExit(DropTargetEvent dte) {
    System.out.println("Source: " + dte.getSource());
    System.out.println("Drag Exit");
    public void dragOver(DropTargetDragEvent dtde) {
    System.out.println("Drag Over");
    public void dropActionChanged(DropTargetDragEvent dtde) {
    System.out.println("Drop Action Changed");
    public void drop(DropTargetDropEvent dtde) {
    FileSystemView view = FileSystemView.getFileSystemView();
    JLabel testb;
    Icon icon = null;
    Toolkit tk;
    Dimension dim;
    BufferedImage buff = null;
    try {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
    System.out.println("Possible flavor: " + flavors.getMimeType());
    if (flavors[i].isFlavorJavaFileListType()) {
    dtde.acceptDrop(DnDConstants.ACTION_COPY);
    ta.setText("Successful file list drop.\n\n");
    java.util.List list = (java.util.List) tr.getTransferData(flavors[i]);
    for (int j = 0; j < list.size(); j++) {
    System.out.println(list.get(j));
    file = (File) list.get(j);
    icon = view.getSystemIcon(file);
    ta.append(list.get(j) + "\n");
    ta.append("\n");
    tk = Toolkit.getDefaultToolkit();
    dim = tk.getBestCursorSize(icon.getIconWidth(), icon.getIconHeight());
    buff = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
    icon.paintIcon(ta, buff.getGraphics(), 10, 10);
    repaint();
    dtde.dropComplete(true);
    return;
    System.out.println("Drop failed: " + dtde);
    dtde.rejectDrop();
    } catch (Exception e) {
    e.printStackTrace();
    dtde.rejectDrop();
    public static void main(String args[]) {
    new FileDrag();

    I want to drag and drop a file to a JText area with its system file icon , but the problem is I cant show the file icon.
    Anyone knows this.
    this is my code.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.DnDConstants;
    import java.awt.dnd.DropTarget;
    import java.awt.dnd.DropTargetDragEvent;
    import java.awt.dnd.DropTargetDropEvent;
    import java.awt.dnd.DropTargetEvent;
    import java.awt.dnd.DropTargetListener;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    public class FileDrag extends JFrame implements DropTargetListener {
    DropTarget dt;
    File file;
    JTextArea ta;
    JLabel lbl;
    Graphics g;
    ImageIcon tmpIcon;
    public FileDrag() {
    super("Drop Test");
    setSize(300, 300);
    getContentPane().add(
    new JLabel("Drop a list from your file chooser here:"),
    BorderLayout.NORTH);
    ta = new JTextArea();
    ta.setBackground(Color.white);
    getContentPane().add(ta);
    dt = new DropTarget(ta, this);
    setVisible(true);
    public void dragEnter(DropTargetDragEvent dtde) {
    System.out.println("Drag Enter");
    public void dragExit(DropTargetEvent dte) {
    System.out.println("Source: " + dte.getSource());
    System.out.println("Drag Exit");
    public void dragOver(DropTargetDragEvent dtde) {
    System.out.println("Drag Over");
    public void dropActionChanged(DropTargetDragEvent dtde) {
    System.out.println("Drop Action Changed");
    public void drop(DropTargetDropEvent dtde) {
    FileSystemView view = FileSystemView.getFileSystemView();
    JLabel testb;
    Icon icon = null;
    Toolkit tk;
    Dimension dim;
    BufferedImage buff = null;
    try {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
    System.out.println("Possible flavor: " + flavors.getMimeType());
    if (flavors[i].isFlavorJavaFileListType()) {
    dtde.acceptDrop(DnDConstants.ACTION_COPY);
    ta.setText("Successful file list drop.\n\n");
    java.util.List list = (java.util.List) tr.getTransferData(flavors[i]);
    for (int j = 0; j < list.size(); j++) {
    System.out.println(list.get(j));
    file = (File) list.get(j);
    icon = view.getSystemIcon(file);
    ta.append(list.get(j) + "\n");
    ta.append("\n");
    tk = Toolkit.getDefaultToolkit();
    dim = tk.getBestCursorSize(icon.getIconWidth(), icon.getIconHeight());
    buff = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
    icon.paintIcon(ta, buff.getGraphics(), 10, 10);
    repaint();
    dtde.dropComplete(true);
    return;
    System.out.println("Drop failed: " + dtde);
    dtde.rejectDrop();
    } catch (Exception e) {
    e.printStackTrace();
    dtde.rejectDrop();
    public static void main(String args[]) {
    new FileDrag();

  • Drag and drop several files

    Hi,
    I'm using iPhoto '11 (version 9.4.2) and when I try to drag and drop several files into a folder, it fails.
    Actually it just does nothing: the drag and drop icon is created with the accurate numbre of items in a red star, the folder blinks but when I release the mouse, nothing happens.
    It fails sometimes with 3 photos, sometimes with 30.
    What's more puzzling is that it sometimes works: if I drag and drop of a single photo it always works. And I'm sometimes able to drop 10 or more photos.
    I'm running on a macbook pro retina with lion (10.8.2).
    Any idea of logs I could look at for some informations, some errors messages?
    Thanks,
    Laurent.

    I guess it creates new photos, hence it modifies the timestamps whereas drag and drop does not.
    There are two kinds of metadata involved when you consider  jpeg or other image file.
    One is the file data. This is what the Finder shows. This tells you nothing about the contents of the file, just the File itself.
    The problem with File metadata is that it can easily change as the file is moved from place to place or exported, e-mailed, uploaded etc.
    Photographs have also got both Exif and IPTC metadata. The date and time that your camera snapped the Photograph is recorded in the Exif metadata. Regardless if what the file date says, this is the actual time recorded by the camera.
    Photo applications like iPhoto, Aperture, Lightroom, Picasa, Photoshop etc get their date and time from the Exif metadata.
    When you export from iPhoto to the Finder new file is created containing your Photo (and its Exif). The File date is - quite accurately - reported as the date of Export. However, the Photo Date doesn't change.
    The problem is that the Finder doesn't work with Exif.
    So, your photo has the correct date, and so does the file, but they are different things. To sort on the Photo date you'll need to use a photo app.

  • I want to drag and drop a file to a JText area with its file icon

    I want to drag and drop a file to a JText area with its file icon , but the problem is I cant show the file icon.
    Anyone knows this.
    this is my code.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.dnd.DnDConstants;
    import java.awt.dnd.DropTarget;
    import java.awt.dnd.DropTargetDragEvent;
    import java.awt.dnd.DropTargetDropEvent;
    import java.awt.dnd.DropTargetEvent;
    import java.awt.dnd.DropTargetListener;
    import java.io.File;
    import javax.swing.*;
    import javax.swing.filechooser.FileSystemView;
    public class FileDrag extends JFrame implements DropTargetListener {
    DropTarget dt;
    File file;
    JTextArea ta;
    JLabel lbl;
    Graphics g;
    ImageIcon tmpIcon;
    public FileDrag() {
    super("Drop Test");
    setSize(300, 300);
    getContentPane().add(
    new JLabel("Drop a list from your file chooser here:"),
    BorderLayout.NORTH);
    ta = new JTextArea();
    ta.setBackground(Color.white);
    getContentPane().add(ta);
    dt = new DropTarget(ta, this);
    setVisible(true);
    public void dragEnter(DropTargetDragEvent dtde) {
    System.out.println("Drag Enter");
    public void dragExit(DropTargetEvent dte) {
    System.out.println("Source: " + dte.getSource());
    System.out.println("Drag Exit");
    public void dragOver(DropTargetDragEvent dtde) {
    System.out.println("Drag Over");
    public void dropActionChanged(DropTargetDragEvent dtde) {
    System.out.println("Drop Action Changed");
    public void drop(DropTargetDropEvent dtde) {
    FileSystemView view = FileSystemView.getFileSystemView();
    JLabel testb;
    Icon icon = null;
    Toolkit tk;
    Dimension dim;
    BufferedImage buff = null;
    try {
    Transferable tr = dtde.getTransferable();
    DataFlavor[] flavors = tr.getTransferDataFlavors();
    for (int i = 0; i < flavors.length; i++) {
    System.out.println("Possible flavor: " + flavors.getMimeType());
    if (flavors.isFlavorJavaFileListType()) {
    dtde.acceptDrop(DnDConstants.ACTION_COPY);
    ta.setText("Successful file list drop.\n\n");
    java.util.List list = (java.util.List) tr.getTransferData(flavors);
    for (int j = 0; j < list.size(); j++) {
    System.out.println(list.get(j));
    file = (File) list.get(j);
    icon = view.getSystemIcon(file);
    ta.append(list.get(j) + "\n");
    ta.append("\n");
    tk = Toolkit.getDefaultToolkit();
    dim = tk.getBestCursorSize(icon.getIconWidth(), icon.getIconHeight());
    buff = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
    icon.paintIcon(ta, buff.getGraphics(), 10, 10);
    repaint();
    dtde.dropComplete(true);
    return;
    System.out.println("Drop failed: " + dtde);
    dtde.rejectDrop();
    } catch (Exception e) {
    e.printStackTrace();
    dtde.rejectDrop();
    public static void main(String args[]) {
    new FileDrag();
    }

    This appears to be a long-standing bug:
    https://bugzilla.mozilla.org/show_bug.cgi?id=634720
    and the accepted workaround is stated in comment 11.
    Oddly, it's possible to do the reverse, i.e. drag multiple eml files from Explorer to a TB folder.

  • I am unable to drag and drop image files in a JAVA supposrted site. I have all the lastest versions of softwarte here - everything is up to date.

    I am no longer able to drag and drop image files int this JAVA supported site. It had always worked flawlessly in the past.
    I would open the site, go to Send Files, allow access, fill out the fields and then drag and drop my image files. Now I can only use the ADD (+) button to do so.
    I have the latest versions of OS-X Lion and JAVA installed on my computer
    http://www.clippingprovider.com/CP_II_EU/Welcome.html

    This is the Tech Sheet on the subject:
    Photoshop Help | Managing paths
    It contains this item under Manage Paths:
    When you use a pen or shape tool to create a work path, the new path appears as the work path in the Paths panel. The work path is temporary; you must save it to avoid losing its contents.
    Ok, the red you referred to is a Stoke you added. Then QuickMask is not involved.

  • Why cant i drag and drop mp3 files into my itunes library in itunes 11.1.1?

    I recently lost a hard drive with most of my music on it. i removed and reinstalled itunes and set it to work on my other hard drive. i was able to drag and drop mp3 files that i had and put them into my library. After the latest updates, now it only gives my the cirlcle with the slash though it when i try, not sure what changed

    did you manage to fix your problem.
    i tunes 6 used to be great for me but i upgraded to 7 which wiped my i tunes and ipod. im back to ver 6 now but i cant drag files from my c drive to any playlists

  • I just downloaded the new version of iTunes 10 and now it won't let me drag and drop any files from my computer.

    I just downloaded the new version of iTunes 10 and now it won't let me drag and drop any files from my computer into my iTunes. It lets me play the song from the folder in my computer and then it opens with iTunes and plays the song all the way through, but then if I try to play it again, it says the file cannot be located. So then I go to locate and go to the folder and all that and select it and nothing happens.

    Not sure whether for instance you initially had a Yahoo optimised version of Firefox, and have now overwritten it with an official Mozilla version. Although the Mozilla version should NOT add unwanted features, but the Yahoo version may well do.
    If you merely need to find the Yahoo emails page quickly just add it as a bookmark or as a bookmark on the Bookmarks toolbar and make sure that is visible.
    Clicking the star icon on the location bar whilst looking at your emails will bookmark the page.
    * [[How to use bookmarks to save and organize your favorite websites]]
    * [[Bookmarks Toolbar - Display your favorite websites at the top of the Firefox window]]
    I do not use Yahoo myself,and am not sure what add-ons are available. You could search yourself using
    * FirefoxButton -> add-ons
    ** see [[Find and install add-ons to add features to Firefox]]
    ** examples [https://addons.mozilla.org/en-us/firefox/addon/yahoo-toolbar/ yahoo toolbar] & [https://addons.mozilla.org/en-us/firefox/addon/yahoo-mail-notifier/ mail notifier]
    * also look at Yahoo's own information such as http://help.yahoo.com/tutorials/toolbar/cl3/c3_ff_toolbar1.html

  • Drag and Drop from LR to other applications

    There was a thread going on D&D from LR to explorer.
    The other appliation problem I have is the apparent inability to drag and drop from lightroom into a file transfer window (e.g., file upload with SmugMug).
    The quick collection is an awesome way to organize a storyline of images from a shoot, select only the images needed, and prepare a shoot for upload. However, short of exporting to a folder first, is there a way to just drag and drop the file set from a LR view (filmstrip or thumbs) to another app? This would just be providing file handles, and I would be satisfied if it only grabbed the original images (pre-"develop").
    Anyone have any luck with this?
    -- Jeff

    No. And not likely anytime soon. Putting a Pointer/alias to SmugMug (if it is an uploader client app, not familiar with it) in the Export Actions Folder for Post Processing from Export is the best you can do at the monemt. To get LR rdits out of LR you have to Export. D&D just isn't going to do that for you.
    Don
    Don Ricklin, MacBook 1.83Ghz Duo 2 Core running 10.4.9 & Win XP, Pentax *ist D
    http://donricklin.blogspot.com/

  • I can't drag and drop mp3 files directly to my shuffle

    i have a ipod shuffle (2nd gen). i cant drag and drop mp3 files via itunes. it only allows me to put them into library and then sync it. but i dont want to sync, i just want to put mp3s directly into shuffle.
    thanks

    thanks for the patiance
    with my old ipod (ipod nano 1st gen) i could easily drag and drop my mp3s from windows explorer to ipod by using itunes. is it itunes new version problem so that i couldnt drag and drop manually, or ipod shuffle problem.
    thanks again.

  • I can't drag and drop word files to a folder

    I can't drag and drop word files to a folder. When I click and hold over a file, nothing happens. Normally it goes where I drag it.

    thanks for the patiance
    with my old ipod (ipod nano 1st gen) i could easily drag and drop my mp3s from windows explorer to ipod by using itunes. is it itunes new version problem so that i couldnt drag and drop manually, or ipod shuffle problem.
    thanks again.

  • How can i sync videos to my iphone 5 using Itunes 11. i also tried to convert the videos to mp4 and drag and drop the file in itunes but still i cant see videos in itunes library.

    how can i sync videos to my iphone 5 using Itunes 11. i also tried to convert the videos to mp4 and drag and drop the file in itunes but still i cant see videos in itunes library.

    Copied from this link.
    http://www.apple.com/iphone/specs.html
    Video formats supported: H.264 video up to 1080p, 30 frames per second, High Profile level 4.1 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; MPEG-4 video up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps per channel, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats; Motion JPEG (M-JPEG) up to 35 Mbps, 1280 by 720 pixels, 30 frames per second, audio in ulaw, PCM stereo audio in .avi file format
    There are 3rd party utilities available that "rip" content into a compatible format - most include an iPod and/or iPhone format selection. If a video plays in iTunes, iTunes includes an option to convert a selection for iPod/iPhone.

  • Drag and Drop or file attachment in Adobe Forms Central

    Is there a particular form or field type in Adobe Forms Central that would allow a user to "attach" or drag and drop a file to a form...say a blueprint?

    Hi,
    Yes. FormsCentral HTML forms support a File Attachment field. The following page provides an overview:
    https://www.acrobat.com/formscentral/en/library/attachments.html
    Regards,
    Brian

  • Why can I no longer drag and drop .mid files into GB?

    I can no longer drag and drop .mid files into GB. When I try, the track files flash and disappear. Please help
    Mac mini   Mac OS X (10.4.6)  

    found solution, thanx everyone

  • I download firefox 5.0 and now I'm having trouble dragging and dropping PDF files into Google Docs and I can't view the PDF once uploaded. I had no problems with this in the previous verion of Firefox

    With firefox 5.0 I can't drag and drop pdf files in the google docs screen. When I do eventually get a pdf file uploaded I can't view it. I get "no preview available". In my previous verion of firefox (4.something) I had no problems with this and I was able to drag and drop and after uploaded I could view the entire file.

    Thanks one again. I know you helped me the last to. I do have the Deja Vu font set in my folder. I downloaded and the last time. So I don't know if there is supposed to be more or not, but those were installed with Windows-XP after my reformat.
    This is really driving me nuts. as I've done several re-formats on my computer and several friends computers and even upgraded hardware so I am not necessarily a software or programming expert, I am somewhat advanced when it comes to computers in general and can usually diagnose the problem but these font's are the problem and they never were before.
    I did see in another forum that if you had a Dell Computer and did the Microsoft update for the onboard video card driver that it could be the culprit, but I have that disabled being I have a much better graphics card so the updates from Microsoft for the onboard video weren't installed.
    It' a Dell Dimension 3000 with an Intel(R) 82865G Graphics Controller so I don't believe it is the culprit being it is disabled. The actual video card that I am using is a PCI Nvidia GeForce 9400 GT with 1 GB Memory. And I didn't have any problem before.
    I appreciate the help. But still can't get things to work. Live Help Chat doesn't open for another two hours so maybe they can do "Remote Access" or something and can check setting and help me. But if you come up with other suggestions, they would be greatly appreciated.
    Thanks again.
    Susan

  • Set default import format when drag and drop sound file into multitrack view?

    I've looked around the preference panels but cannot find where to set the import settings for dragging and dropping sound files into multitrack view. Some of our computers have correct settings and others do not. Thanks for your help!
    G

    I should have been more specific, sorry... I mean bit depth and bit rate... On some machines this defaults correctly and on other machines it is wrong. Not sure how to set these to downconvert properly by default. Unless it automatically takes the format of the source file, in which case it's just been luck.
    Thanks,
    G

Maybe you are looking for

  • Highlighted Cell

    i know it just a command but i do not how. when i open a table..how to make it automatically the first row of the table will be highlighted? Nice day and thanks for viewing

  • Submit Form Anonymously?

    I have been searching for a solution to this question on a few forums, but with no success. It seems everytime I find this topic the submitter gets no response. (hopefully not in this case) We have a feedback form for the user to fill out after watch

  • Dropping my connection every weekday evening

    Hi all, looking for some help with my connection. For the past hmm... it's been a while maybe eight weeks something like that, i've been losing my connection once between 21:00 and 22:00 it happens every night. It's often closer two nine, for a whole

  • 3000N100- Tray-Bluet​ooth-icon shows red 'B' - not sure how to fix it

    Hi,   Could some one please help me with any pointers or links to troubleshoot the Bluetooth-tray-icon on my Lenovo 3000N100? Currently it is showing a red "B" indicating a problem with the bluetooth. Unsure how to get it fixed/troubleshooted. Could

  • Microphone doesn't appear in the Device Manager in Windows 7

    I'm using Windows 7 64 Bit OS on my MacBook Pro, clean installation, not based on Bootcamp, no MAC OS installed (required by our company otherwise I can't access corp network). Now my problem is that the speakers are working properly, but I can't use