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承诺的副本 2018-04-19 10:07:24.238 java [91646:4228080]在粘贴板上查找了HFSPromises,但没有找到。
例如,从桌面删除的文件将被接受。有什么想法吗?