java 实现拖动文件到窗口功能
Posted 猫儿爹
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 实现拖动文件到窗口功能相关的知识,希望对你有一定的参考价值。
package tuo; import java.awt.BorderLayout; import java.awt.Color; 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.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class tuo extends JFrame{ JPanel jp1; public tuo() { jp1 =new JPanel(); jp1.setBackground(Color.yellow); getContentPane().add(jp1,BorderLayout.CENTER); setSize(500,200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocation(400,200); setTitle("tuozhuai"); drag(); } public static void main(String[] args) { // TODO Auto-generated method stub try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { // TODO Auto-generated catch block e.printStackTrace(); } new tuo().setVisible(true); } public void drag() { new DropTarget(jp1,DnDConstants.ACTION_COPY_OR_MOVE,new DropTargetAdapter() { @Override public void drop(DropTargetDropEvent dtde) { try{ if(dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); 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); } } else { dtde.rejectDrop(); } }catch(Exception e){e.printStackTrace();} } }); } }
以上是关于java 实现拖动文件到窗口功能的主要内容,如果未能解决你的问题,请参考以下文章