Java implementation of drag and drop example
The drag and drop function is implemented in Swing. The code is very simple and has comments. See for yourself. The running effect is as follows:
Copy the code code as follows:
package com;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import java.io.File;
import java.util.List;
import javax.swing.*;
/**
* The simplest Java drag and drop code example
* @author Liu Xianan
* January 24, 2013
*/
public class DragTest extends JFrame
{
JPanel panel;//Panel to accept drag and drop
public DragTest()
{
panel = new JPanel();
panel.setBackground(Color.YELLOW);
getContentPane().add(panel, BorderLayout.CENTER);
setSize(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(400, 200);
setTitle("The simplest drag and drop example: drag and drop the file below (20130124)");
drag();//Enable drag and drop
}
public static void main(String[] args) throws Exception
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");//Set the skin
new DragTest().setVisible(true);;
}
public void drag()//Drag method defined
{
//Panel represents the control to be dragged and dropped
new DropTarget(panel, DnDConstants.ACTION_COPY_OR_MOVE, new DropTargetAdapter()
{
@Override
public void drop(DropTargetDropEvent dtde)//Rewrite the adapter’s drop method
{
try
{
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor))//If the dragged file format is supported
{
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);//Receive the dragged data
List<File> list = (List<File>) (dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor));
String temp="";
for(File file:list)
temp+=file.getAbsolutePath()+";/n";
JOptionPane.showMessageDialog(null, temp);
dtde.dropComplete(true);//Indicates that the drag and drop operation has been completed
}
else
{
dtde.rejectDrop(); // Otherwise, reject the dragged data
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}