Explore Java Hacks and Tutorials
Be Social. Be Updated.

Drag and Drop a File in JTextArea

Using the AWT DND option for drag and drop in JTextArea
Here is a very simple example for dragging and dropping a file in JTextArea. The aim of the program is when a file from outside is dropped in the JTextArea, the JTextArea has to read the content of the file and display the text in it. Hope, this is what you are looking for.

For this, you will notice the java.awt.dnd package which contains some classes that does the job.

import java.awt.dnd.*;
import java.awt.*;
import javax.swing.*;
import java.awt.datatransfer.*;
import java.io.*;
class DragAndDrop extends JFrame
private JTextArea jt;
    public DragAndDrop()
    private void createAndShowGUI()
    setTitle("Drag and Drop Example");
    setLayout(new BorderLayout());
    // Create JTextArea
    jt=new JTextArea();
    private void enableDragAndDrop()
        DropTarget target=new DropTarget(jt,new DropTargetListener(){
            public void dragEnter(DropTargetDragEvent e)
            public void dragExit(DropTargetEvent e)
            public void dragOver(DropTargetDragEvent e)
            public void dropActionChanged(DropTargetDragEvent e)
            public void drop(DropTargetDropEvent e)
                    // Accept the drop first, important!
                    // Get the files that are dropped as java.util.List
                    java.util.List list=(java.util.List) e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
                    // Now get the first file from the list,
                    File file=(File)list.get(0);
                    jt.read(new FileReader(file),null);
                }catch(Exception ex){}
    static public void main(String args[])
        new DragAndDrop();

Explaining DragAndDrop

ACTION_COPY_MOVE: Copy or Move does not make sense in case of dragging and dropping of files. You can also use ACTION_COPY or ACTION_MOVE. The user can also select the drop action with several shortcuts as mentioned in DropTargetDragEvent.

e.getTransferable(): This method gets the Transferable object which contains the getTransferData() method which takes the DataFlavor object. We need not create an object for this instead we can just use the available DataFlavor constants. The flavors available are stringFlavor, plainTextFlavor (Deprecated), imageFlavor, javaFileListFlavor.

We have used the javaFileListFlavor which returns java.util.List containing the files that are dropped.

jt.read(new FileReader(fr),null); This method in the JTextComponent takes a Reader object and set's the contents of that reader in it. The second parameter is description which is not necessary here.
static public void main(String args[]): Just to be quite different.

Posted by at on

Tags: Abstract Window Toolkit Drag and Drop Swing Components