我有一个带有大量图形元素的 SWT 应用程序。我希望用户能够将元素拖动到桌面/Windows 资源管理器/OS X Finder。当他们放置该元素时,我需要他们将其放置到的路径,以便我可以在该位置创建一个代表该元素的文件。
我认为我无法使用FileTransfer
,因为没有源文件。有一个源对象可以创建文件,但只有当它知道将文件放在哪里时。
下面内联的是我想要实现的一个简单示例,有一个文本框,其中带有可以从中拖动的标签。如果用户拖动到某个文件夹或文件,我想获取他们拖动到的路径。如果他们拖动到一个文件,我想用文本框中的内容替换该文件的内容。如果它们拖到一个文件夹,我想创建一个名为“TestFile”的文件,其中包含文本框中的任何内容。
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class DesktopDragExample {
public static void main(String[] args) {
// put together the SWT main loop
final Display display = Display.getDefault();
display.syncExec(new Runnable() {
@Override
public void run() {
Shell shell = new Shell(display, SWT.SHELL_TRIM);
initializeGui(shell);
//open the shell
shell.open();
//run the event loop
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
});
}
// create the gui
private static void initializeGui(Composite parent) {
GridLayout layout = new GridLayout(2, false);
parent.setLayout(layout);
// make the instructions label
Label infoLbl = new Label(parent, SWT.WRAP);
GridData gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
gd.horizontalSpan = 2;
infoLbl.setLayoutData(gd);
infoLbl.setText(
"You should be able to drag to the desktop, Windows Explorer, or OS X Finder.\n" +
"If you drag to a file, it will replace the contents of that file with the contents of the text box.\n" +
"If you drag to a folder, it will create a file named 'TestFile' whose contents are whatever is in the text box.");
// make the text element
final Text text = new Text(parent, SWT.SINGLE | SWT.BORDER);
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
text.setLayoutData(gd);
// make the label element
Label label = new Label(parent, SWT.NONE);
label.setText("Drag me");
// listener for drags
DragSourceListener dragListener = new DragSourceListener() {
@Override
public void dragStart(DragSourceEvent e) {
e.detail = DND.DROP_COPY;
}
@Override
public void dragFinished(DragSourceEvent e) {
System.out.println("--dragFinished--");
System.out.println("e.data=" + e.data);
}
@Override
public void dragSetData(DragSourceEvent e) {
System.out.println("--dragSetData--");
System.out.println("e.data=" + e.data);
}
};
// the DragSource
DragSource dragSource = new DragSource(label, DND.DROP_COPY);
dragSource.setTransfer(new Transfer[]{FileTransfer.getInstance()});
dragSource.addDragListener(dragListener);
}
private static void draggedTo(String path, String textBoxContents) {
System.out.println("Dragged the contents '" + textBoxContents + "' to '" + path + "'");
}
}
其他一些人也遇到了同样的问题,但到目前为止似乎还没有解决方案: Drag from SWT to Desktop , ..want destination path as String
最佳答案
唯一的方法是创建一个临时文件,然后使用 FileTransfer。我怀疑这就是你必须在 native 代码中执行的操作。我会看看是否有足够的时间来绘制示例草图......
关于java - SWT 拖动到资源管理器 (Windows) 或 Finder (OS X),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16246242/