swing支持文件和文件夹拖放的自定义TextField

上网搜了下各种相关教程,有种想骂人的冲动。

你自己搞不懂也就算了,本来挺简单的一码事,

还故意整得跟天书一样。显摆自己高深?

我去年买了个表。

不多说了,上代码。

import javax.swing.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.*;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: hp
 * Date: 14-3-19
 * Time: 下午7:30
 * To change this template use File | Settings | File Templates.
 */
public class DragTextField extends JTextField implements DropTargetListener {
    public DragTextField( int columns ) {
        super( columns );
        new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
    }

    @Override
    public void dragEnter( DropTargetDragEvent dtde ) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void dragOver( DropTargetDragEvent dtde ) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void dropActionChanged( DropTargetDragEvent dtde ) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void dragExit( DropTargetEvent dte ) {
        //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public void drop( DropTargetDropEvent event ) {
        try {
            if (event.isDataFlavorSupported( DataFlavor.javaFileListFlavor)) {
                event.acceptDrop( DnDConstants.ACTION_COPY_OR_MOVE );
                List list = (List)event.getTransferable()
                        .getTransferData(DataFlavor.javaFileListFlavor);
                Iterator iterator = list.iterator();
                while (iterator.hasNext()) {
                    setText("");
                    File f = (File)iterator.next();
                    setText(f.getAbsolutePath() + "\n");
                }
                event.dropComplete( true );
                updateUI();
            } else {
                event.rejectDrop();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (UnsupportedFlavorException ufe) {
            ufe.printStackTrace();
        }//To change body of implemented methods use File | Settings | File Templates.
    }
}

看到了吧,非常简单,就实现个接口,

然后从event对象中获取拖放的内容。

你可能感兴趣的:(textfield)