Sample drag and drop functionality in Java swing
- 2020-04-01 03:20:14
- OfStack
Java implements the drag and drop example
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201404/20140429104713.png? 2014329104745 ">
Swing drag-and-drop function, the code is very simple, there are comments, you see, the operation effect is 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.*;
public class DragTest extends JFrame
{
JPanel panel;//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(" Simplest drag-and-drop example: drag a file to the following ( 20130124 ) ");
drag();//To enable drag-and-drop
}
public static void main(String[] args) throws Exception
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");//Set up the skin
new DragTest().setVisible(true);;
}
public void drag()//The defined drag and drop method
{
//A panel represents the control to accept drag and drop
new DropTarget(panel, DnDConstants.ACTION_COPY_OR_MOVE, new DropTargetAdapter()
{
@Override
public void drop(DropTargetDropEvent dtde)//Override the adapter's drop method
{
try
{
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor))//If the file format is supported
{
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);//Receive the data from the drag and drop
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 has completed
}
else
{
dtde.rejectDrop();//Otherwise drag and drop data is rejected
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
}