关于拖拽

本文介绍了一个使用Java实现的简单示例,展示了如何通过Drag and Drop功能将文件拖拽到JFrame中,并读取拖入的文件列表。此示例利用了Java的AWT和Swing库,通过DropTarget和DropTargetListener接口实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package testexcel;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
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.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
 *
 * @author 91152
 */
public class Test1 {
    private void init(){
        JFrame jf = new JFrame("测试拖拽");
        jf.setSize(400, 400);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
        //新建一个DropTarget对象
        new DropTarget(jf,DnDConstants.ACTION_COPY,new BenDropTargetListener());
    }
    
    public static void main(String[] args) {
        new Test1().init();
    }
    
    class BenDropTargetListener extends DropTargetAdapter{

        @Override
        public void drop(DropTargetDropEvent dtde) {
            File file = null;

            //下面这一句不写就会报错,导致下面无法获取fileList
            dtde.acceptDrop(DnDConstants.ACTION_COPY);
            
            Transferable tf = dtde.getTransferable();
            DataFlavor[] df = dtde.getCurrentDataFlavors();
            //为什么要做下面的判断?因为非常有可能拖入其他的类型,比如文本类型
            //那么,如果没有javaFileListeFlavor类型的话,就没有下面的步骤了
            for(int i = 0; i < df.length; i++){
                DataFlavor ddf = df[i];
                if(ddf.equals(DataFlavor.javaFileListFlavor)){
                    try {
                        List fileList = (List)tf.getTransferData(ddf);
                        for(Object f:fileList){
                            file = (File)f;
                            System.out.println(file.getAbsoluteFile());
                        }
                        
                    } catch (UnsupportedFlavorException ex) {
                        Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
        
    } 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值