先看一个例子:

核心代码:
/***
* 拖拽文件到文本框
* @param component
*/
public void drag(final component component)// 定义的拖拽方法
{
// panel表示要接受拖拽的控件
new droptarget(component, dndconstants.action_copy_or_move,
new droptargetadapter() {
@override
public void drop(droptargetdropevent dtde)// 重写适配器的drop方法
{
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);
dragresponse(list,component);
dtde.dropcomplete(true);// 指示拖拽操作已完成
} else {
dtde.rejectdrop();// 否则拒绝拖拽来的数据
}
} catch (exception e) {
e.printstacktrace();
}
}
});
}
* 默认实现
@override
protected void dragresponse(list<file> list,component component) {
string filepath=list.get(0).getabsolutepath();
if(component instanceof jtextcomponent){
jtextcomponent text=(jtextcomponent)component;
//把文本框的内容设置为拖拽文件的全路径
text.settext(filepath);
}
调用:
项目采用maven 构建,项目结构: