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

查看:72
本文介绍了如何在 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() 回调.在此回调中,您需要检查 Transferable 的 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,Transferable类型会有所不同

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, "
"); 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天全站免登陆