import java.awt.*;
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 java.util.ArrayList;
import javax.swing.*;
public class DragDropNewActivity extends JFrame implements DropTargetListener {
DropTarget dt;
public DragDropNewActivity()
{
setSize(400,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblDraganddrop = new JLabel("Drag And Drop here");
lblDraganddrop.setHorizontalTextPosition(SwingConstants.CENTER);
lblDraganddrop.setHorizontalAlignment(SwingConstants.CENTER);
lblDraganddrop.setFont(new Font("Tahoma",Font.PLAIN,32));
getContentPane().add(lblDraganddrop, BorderLayout.CENTER);
dt = new DropTarget (lblDraganddrop, this);
setVisible(true);
}
@Override
public void drop(DropTargetDropEvent dtde)
{
try
{
Transferable tr = dtde.getTransferable();
DataFlavor[] flavors = tr.getTransferDataFlavors();
ArrayList<File> fileNames = new ArrayList<File>();
for (int i = 0; i < flavors.length; i++)
{
if (flavors[i].isFlavorJavaFileListType())
{
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
@SuppressWarnings("unchecked")
java.util.List<File> files = (java.util.List<File>) tr.getTransferData(flavors[i]);
for (int k = 0; k < files.size(); k++)
{
fileNames.add(files.get(k));
// Write the filename/s on console output.
System.out.println(files.get(k));
//Parse through new file
//new DragDropNewActivityParse().parseThroughFile(files.get(k));
}
dtde.dropComplete(true);
}
}
}
catch (Throwable t)
{
t.printStackTrace();
}
dtde.rejectDrop();
}
@Override
public void dragEnter(DropTargetDragEvent dtde)
{}
@Override
public void dragOver(DropTargetDragEvent dtde)
{}
@Override
public void dropActionChanged(DropTargetDragEvent dtde)
{}
@Override
public void dragExit(DropTargetEvent dte)
{}
}
在 Windows 中它可以正常工作。在 Mac OS HighSierra(13.4) 中,它不接受来自 Apple Mail 应用程序的文件。每次尝试从 Apple Mail 应用程序中删除文件时,都会在控制台中写入缺少 HFS 承诺错误。
控制台输出:2018-04-19 10:07:24.237 java[91646:4228080] 无法从粘贴板中获取 HFS Promise 的副本 2018-04-19 10:07:24.238 java[91646:4228080] 寻找粘贴板上的 HFSPromises,但没有找到。
例如,从桌面删除的文件将被接受。有任何想法吗?