如何在Swing中使用拖放来获取文件路径? [英] How can I use Drag-and-Drop in Swing to get file path?

查看:550
本文介绍了如何在Swing中使用拖放来获取文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的swing应用程序中有一个JTextField,它保存选定要使用的文件的文件路径。目前我有一个JFileChooser用于填充这个值。但是,我想添加一个用户将文件拖放到此JTextField上的功能,并将该文件的文件路径放置到JTextField中,而不是始终使用JFileChooser。

I have a JTextField in my swing application that holds the file path of a file selected to be used. Currently I have a JFileChooser that is used to populate this value. However, I would like to add the ability for a user to drag-and-drop a file onto this JTextField and have it place the file path of that file into the JTextField instead of always having using the JFileChooser.

如何做?

推荐答案

首先你应该研究一下 Swing DragDrop支持。之后,对于不同的操作系统,几乎没有什么技巧。一旦你有事情进行,你将处理drop()回调。在这个回调中,您将要查看可转移的DataFlavor。

First you should look into Swing DragDrop support. After that there are few little tricks for different operating systems. Once you've got things going you'll be handling the drop() callback. In this callback you'll want to check the DataFlavor of the Transferable.

对于Windows,您只需检查 DataFlavor.isFlavorJavaFileListType(),然后获取这样的数据

For Windows you can just check the DataFlavor.isFlavorJavaFileListType() and then get your data like this

List<File> dropppedFiles = (List<File>)transferable.getTransferData(DataFlavor.javaFileListFlavor)

对于Linux Solaris)DataFlavor有点棘手。您将需要自己创建DataFlavor并且可转移类型将不同

For Linux (and probably Solaris) the DataFlavor is a little trickier. You'll need to make your own DataFlavor and the Transferable type will be different

nixFileDataFlavor = new DataFlavor("text/uri-list;class=java.lang.String");
String data = (String)transferable.getTransferData(nixFileDataFlavor);
for(StringTokenizer st = new StringTokenizer(data, "\r\n"); st.hasMoreTokens();)
{
    String token = st.nextToken().trim();
    if(token.startsWith("#") || token.isEmpty())
    {
         // comment line, by RFC 2483
         continue;
    }
    try
    {
         File file = new File(new URI(token))
         // store this somewhere
    }
    catch(...)
    {
       // do something good
       ....
    }
}

这篇关于如何在Swing中使用拖放来获取文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆