Java implementation drag-and-drop example
Swing in the implementation of drag-and-drop function, the code is very simple, have comments, see for yourself, the operation effect of the following figure:
Copy 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 Xianhan
* January 24, 2013
*/
public class Dragtest extends JFrame
{
JPanel panel;//to accept drag-and-drop panels
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 the file to the bottom (20130124)");
Drag ()//enable drag-and-drop
}
public static void Main (string[] args) throws Exception
{
Uimanager.setlookandfeel ("Com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");/Set Skin
New Dragtest (). setvisible (true);;
}
The drag method defined by the public void drag ()//
{
Panel indicates that you want to accept the dragged control
New DropTarget (panel, Dndconstants.action_copy_or_move, New Droptargetadapter ()
{
@Override
public void Drop (droptargetdropevent dtde)//Overrides the drop method of the adapter
{
Try
{
if (dtde.isdataflavorsupported (Dataflavor.javafilelistflavor))//If the file format being dragged in is supported
{
Dtde.acceptdrop (Dndconstants.action_copy_or_move)//Receive 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 operation is complete
}
Else
{
Dtde.rejectdrop ()/or refuse to drag the data
}
}
catch (Exception e)
{
E.printstacktrace ();
}
}
});
}
}