たくさんのグラフィカル要素を備えた SWT アプリケーションがあります。ユーザーが要素をデスクトップ/Windows エクスプローラー/OS X Finder にドラッグできるようにしたいと考えています。要素をドロップするときは、要素を表すファイルをその場所に作成できるように、ドロップ先のパスが必要です。
FileTransfer
ソースファイルが無いので使えないと思います。ファイルを作成できるソースオブジェクトがありますが、それをどこに置くかを知っているのは1回だけです。
以下のインラインは、私が達成しようとしていることの簡単な例です。そこからドラッグするラベルが付いたテキスト ボックスがあります。ユーザーがフォルダーまたはファイルにドラッグした場合、ドラッグ先のパスを取得したいと思います。彼らがファイルにドラッグした場合、そのファイルの内容をテキスト ボックスにあるものに置き換えたいと思います。フォルダーにドラッグした場合、テキスト ボックスにある内容を含む "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