首页 > 代码库 > java 实现拖动文件到窗口功能
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 实现拖动文件到窗口功能
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。