public class DragNDrop extends JFrame implements DropTargetListener {
JTextArea textArea = new JTextArea();
DropTarget dt = new DropTarget(textArea, this);
public DragNDrop()
{
textArea.setEditable(false);
textArea.setText("Drag your text file here...");
textArea.setDragEnabled(true);
getContentPane().add(textArea);
}
public static void main(String[] args) {
DragNDrop d = new DragNDrop();
d.setSize(500,500);
d.setTitle("Text-DnD");
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.setVisible(true);
}
public void dragEnter(DropTargetDragEvent arg0) {}
public void dragOver(DropTargetDragEvent arg0) {}
public void dropActionChanged(DropTargetDragEvent arg0) {}
public void dragExit(DropTargetEvent arg0) {}
public void drop(DropTargetDropEvent e) {
textArea.setText("drop");
Transferable tr = e.getTransferable();
DataFlavor[] flavors = tr.getTransferDataFlavors();
textArea.setText("");
for(int i=0; i < flavors.length; i++)
{
if(flavors[i].isFlavorJavaFileListType())
{
e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
try {
List list = (List) tr.getTransferData(flavors[i]);
FileReader fr = new FileReader(list.get(0).toString());
BufferedReader datRead = new BufferedReader(fr);
String text = datRead.readLine();
while(text != null)
{
textArea.append(text + "\n");
text = datRead.readLine();
}
datRead.close();
} catch (UnsupportedFlavorException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
e.dropComplete(true);
return;
}
}
}
}