Java/SWT JFace Eclipse/Drag Drop
Содержание
- 1 Drag and Drop: determine data types available (win32 only)
- 2 Drag and Drop: determine native data types available (motif only)
- 3 Drag and Drop example snippet: define a default operation (in this example, Copy)
- 4 Drag and Drop example snippet: define my own data transfer type
- 5 Drag and Drop example snippet: drag leaf items in a tree
- 6 Drag and Drop example snippet: drag text between two labels
- 7 Illustrates dragging
- 8 Simple DND (Drag and Drop) Example
- 9 SWT DnD (Drag and drop) Composite
- 10 SWT DND (Drag and Drop) comprehensive Example
- 11 Word Jumbles
Drag and Drop: determine data types available (win32 only)
/*
* Drag and Drop example snippet: determine data types available (win32 only)
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.internal.ole.win32.ru;
import org.eclipse.swt.internal.win32.TCHAR;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
public class Snippet83 extends ByteArrayTransfer {
private static Snippet83 _instance = new Snippet83();
private int[] ids;
private String[] names;
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Table control = new Table(shell, SWT.NONE);
TableItem item = new TableItem(control, SWT.NONE);
item
.setText("Drag data over this site to see the native transfer type.");
DropTarget target = new DropTarget(control, DND.DROP_DEFAULT
| DND.DROP_COPY | DND.DROP_LINK | DND.DROP_MOVE);
target.setTransfer(new Transfer[] { Snippet83.getInstance() });
target.addDropListener(new DropTargetAdapter() {
public void dragEnter(DropTargetEvent event) {
String ops = "";
if ((event.operations & DND.DROP_COPY) != 0)
ops += "Copy;";
if ((event.operations & DND.DROP_MOVE) != 0)
ops += "Move;";
if ((event.operations & DND.DROP_LINK) != 0)
ops += "Link;";
control.removeAll();
TableItem item1 = new TableItem(control, SWT.NONE);
item1.setText("Allowed Operations are " + ops);
if (event.detail == DND.DROP_DEFAULT) {
if ((event.operations & DND.DROP_COPY) != 0) {
event.detail = DND.DROP_COPY;
} else if ((event.operations & DND.DROP_LINK) != 0) {
event.detail = DND.DROP_LINK;
} else if ((event.operations & DND.DROP_MOVE) != 0) {
event.detail = DND.DROP_MOVE;
}
}
TransferData[] data = event.dataTypes;
for (int i = 0; i < data.length; i++) {
int id = data[i].type;
String name = getNameFromId(id);
TableItem item2 = new TableItem(control, SWT.NONE);
item2.setText("Data type is " + id + " " + name);
}
}
});
shell.setSize(400, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public static Snippet83 getInstance() {
return _instance;
}
Snippet83() {
ids = new int[80000];
names = new String[80000];
for (int i = 0; i < ids.length; i++) {
ids[i] = i;
names[i] = getNameFromId(i);
}
}
public void javaToNative(Object object, TransferData transferData) {
}
public Object nativeToJava(TransferData transferData) {
return "Hello World";
}
protected String[] getTypeNames() {
return names;
}
protected int[] getTypeIds() {
return ids;
}
static String getNameFromId(int id) {
String name = null;
int maxSize = 128;
TCHAR buffer = new TCHAR(0, maxSize);
int size = COM.GetClipboardFormatName(id, buffer, maxSize);
String type = null;
if (size != 0) {
name = buffer.toString(0, size);
} else {
switch (id) {
case COM.CF_HDROP:
name = "CF_HDROP";
break;
case COM.CF_TEXT:
name = "CF_TEXT";
break;
case COM.CF_BITMAP:
name = "CF_BITMAP";
break;
case COM.CF_METAFILEPICT:
name = "CF_METAFILEPICT";
break;
case COM.CF_SYLK:
name = "CF_SYLK";
break;
case COM.CF_DIF:
name = "CF_DIF";
break;
case COM.CF_TIFF:
name = "CF_TIFF";
break;
case COM.CF_OEMTEXT:
name = "CF_OEMTEXT";
break;
case COM.CF_DIB:
name = "CF_DIB";
break;
case COM.CF_PALETTE:
name = "CF_PALETTE";
break;
case COM.CF_PENDATA:
name = "CF_PENDATA";
break;
case COM.CF_RIFF:
name = "CF_RIFF";
break;
case COM.CF_WAVE:
name = "CF_WAVE";
break;
case COM.CF_UNICODETEXT:
name = "CF_UNICODETEXT";
break;
case COM.CF_ENHMETAFILE:
name = "CF_ENHMETAFILE";
break;
case COM.CF_LOCALE:
name = "CF_LOCALE";
break;
case COM.CF_MAX:
name = "CF_MAX";
break;
}
}
return name;
}
}
Drag and Drop: determine native data types available (motif only)
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.swt.snippets;
/*
* Drag and Drop example snippet: determine native data types available (motif
* only)
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.*;
import org.eclipse.swt.dnd.*;
import org.eclipse.swt.internal.*;
import org.eclipse.swt.internal.motif.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class Snippet158 extends ByteArrayTransfer {
private static Snippet158 _instance = new Snippet158();
private int[] ids;
private String[] names;
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Table control = new Table(shell, SWT.NONE);
TableItem item = new TableItem(control, SWT.NONE);
item
.setText("Drag data over this site to see the native transfer type.");
DropTarget target = new DropTarget(control, DND.DROP_DEFAULT
| DND.DROP_COPY | DND.DROP_LINK | DND.DROP_MOVE);
target.setTransfer(new Transfer[] { Snippet158.getInstance() });
target.addDropListener(new DropTargetAdapter() {
public void dragEnter(DropTargetEvent event) {
String ops = "";
if ((event.operations & DND.DROP_COPY) != 0)
ops += "Copy;";
if ((event.operations & DND.DROP_MOVE) != 0)
ops += "Move;";
if ((event.operations & DND.DROP_LINK) != 0)
ops += "Link;";
control.removeAll();
TableItem item1 = new TableItem(control, SWT.NONE);
item1.setText("Allowed Operations are " + ops);
if (event.detail == DND.DROP_DEFAULT) {
if ((event.operations & DND.DROP_COPY) != 0) {
event.detail = DND.DROP_COPY;
} else if ((event.operations & DND.DROP_LINK) != 0) {
event.detail = DND.DROP_LINK;
} else if ((event.operations & DND.DROP_MOVE) != 0) {
event.detail = DND.DROP_MOVE;
}
}
TransferData[] data = event.dataTypes;
for (int i = 0; i < data.length; i++) {
int id = data[i].type;
String name = getNameFromId(id);
TableItem item2 = new TableItem(control, SWT.NONE);
item2.setText("Data type is " + id + " " + name);
}
}
});
shell.setSize(400, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public static Snippet158 getInstance() {
return _instance;
}
Snippet158() {
}
public void javaToNative(Object object, TransferData transferData) {
}
public Object nativeToJava(TransferData transferData) {
return "Hello World";
}
protected String[] getTypeNames() {
return names;
}
static int shellHandle;
protected int[] getTypeIds() {
if (ids == null) {
Display display = Display.getCurrent();
int widgetClass = OS.topLevelShellWidgetClass();
shellHandle = OS.XtAppCreateShell(null, null, widgetClass,
display.xDisplay, null, 0);
OS.XtSetMappedWhenManaged(shellHandle, false);
OS.XtRealizeWidget(shellHandle);
ids = new int[840];
names = new String[840];
for (int i = 0; i < ids.length; i++) {
ids[i] = i + i;
names[i] = getNameFromId(i + 1);
}
}
return ids;
}
static String getNameFromId(int id) {
int xDisplay = OS.XtDisplay(shellHandle);
int ptr = 0;
try {
ptr = OS.XmGetAtomName(xDisplay, id);
} catch (Throwable t) {
}
if (ptr == 0)
return "invalid " + id;
int length = OS.strlen(ptr);
byte[] nameBuf = new byte[length];
OS.memmove(nameBuf, ptr, length);
OS.XFree(ptr);
return new String(Converter.mbcsToWcs(null, nameBuf)).toLowerCase();
}
}
Drag and Drop example snippet: define a default operation (in this example, Copy)
/*
* Drag and Drop example snippet: define a default operation (in this example, Copy)
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class Snippet84 {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Label label = new Label(shell, SWT.BORDER);
label.setText("Drag Source");
DragSource source = new DragSource(label, DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK);
source.setTransfer(new Transfer[] {TextTransfer.getInstance()});
source.addDragListener(new DragSourceAdapter() {
public void dragSetData(DragSourceEvent event) {
event.data = "Text Transferred";
}
public void dragFinished(DragSourceEvent event) {
if (event.doit) {
String operation = null;
switch (event.detail) {
case DND.DROP_MOVE:
operation = "moved"; break;
case DND.DROP_COPY:
operation = "copied"; break;
case DND.DROP_LINK:
operation = "linked"; break;
case DND.DROP_NONE:
operation = "disallowed"; break;
default:
operation = "unknown"; break;
}
label.setText("Drag Source (data "+operation+")");
} else {
label.setText("Drag Source (drag cancelled)");
}
}
});
final Text text = new Text(shell, SWT.BORDER | SWT.MULTI);
text.setText("Drop Target");
DropTarget target = new DropTarget(text, DND.DROP_DEFAULT | DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK);
target.setTransfer(new Transfer[] {TextTransfer.getInstance()});
target.addDropListener(new DropTargetAdapter() {
public void dragEnter(DropTargetEvent event) {
if (event.detail == DND.DROP_DEFAULT) event.detail = DND.DROP_COPY;
}
public void dragOperationChanged(DropTargetEvent event) {
if (event.detail == DND.DROP_DEFAULT) event.detail = DND.DROP_COPY;
}
public void drop(DropTargetEvent event) {
String operation = null;
switch (event.detail) {
case DND.DROP_MOVE:
operation = "moved"; break;
case DND.DROP_COPY:
operation = "copied"; break;
case DND.DROP_LINK:
operation = "linked"; break;
case DND.DROP_NONE:
operation = "disallowed"; break;
default:
operation = "unknown"; break;
}
text.append("\n"+operation+(String)event.data);
}
});
shell.setSize(400, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Drag and Drop example snippet: define my own data transfer type
/*
* Drag and Drop example snippet: define my own data transfer type
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class Snippet79 {
/*
* The data being transferred is an <bold>array of type MyType</bold> where
* MyType is define as:
*/
static class MyType {
String fileName;
long fileLength;
long lastModified;
}
static class MyTransfer extends ByteArrayTransfer {
private static final String MYTYPENAME = "name_for_my_type";
private static final int MYTYPEID = registerType(MYTYPENAME);
private static MyTransfer _instance = new MyTransfer();
public static MyTransfer getInstance() {
return _instance;
}
public void javaToNative(Object object, TransferData transferData) {
if (!checkMyType(object) || !isSupportedType(transferData)) {
DND.error(DND.ERROR_INVALID_DATA);
}
MyType[] myTypes = (MyType[]) object;
try {
// write data to a byte array and then ask super to convert to
// pMedium
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream writeOut = new DataOutputStream(out);
for (int i = 0, length = myTypes.length; i < length; i++) {
byte[] buffer = myTypes[i].fileName.getBytes();
writeOut.writeInt(buffer.length);
writeOut.write(buffer);
writeOut.writeLong(myTypes[i].fileLength);
writeOut.writeLong(myTypes[i].lastModified);
}
byte[] buffer = out.toByteArray();
writeOut.close();
super.javaToNative(buffer, transferData);
} catch (IOException e) {
}
}
public Object nativeToJava(TransferData transferData) {
if (isSupportedType(transferData)) {
byte[] buffer = (byte[]) super.nativeToJava(transferData);
if (buffer == null)
return null;
MyType[] myData = new MyType[0];
try {
ByteArrayInputStream in = new ByteArrayInputStream(buffer);
DataInputStream readIn = new DataInputStream(in);
while (readIn.available() > 20) {
MyType datum = new MyType();
int size = readIn.readInt();
byte[] name = new byte[size];
readIn.read(name);
datum.fileName = new String(name);
datum.fileLength = readIn.readLong();
datum.lastModified = readIn.readLong();
MyType[] newMyData = new MyType[myData.length + 1];
System
.arraycopy(myData, 0, newMyData, 0,
myData.length);
newMyData[myData.length] = datum;
myData = newMyData;
}
readIn.close();
} catch (IOException ex) {
return null;
}
return myData;
}
return null;
}
protected String[] getTypeNames() {
return new String[] { MYTYPENAME };
}
protected int[] getTypeIds() {
return new int[] { MYTYPEID };
}
boolean checkMyType(Object object) {
if (object == null || !(object instanceof MyType[])
|| ((MyType[]) object).length == 0) {
return false;
}
MyType[] myTypes = (MyType[]) object;
for (int i = 0; i < myTypes.length; i++) {
if (myTypes[i] == null || myTypes[i].fileName == null
|| myTypes[i].fileName.length() == 0) {
return false;
}
}
return true;
}
protected boolean validate(Object object) {
return checkMyType(object);
}
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Label label1 = new Label(shell, SWT.BORDER | SWT.WRAP);
label1.setText("Drag Source for MyData[]");
final Label label2 = new Label(shell, SWT.BORDER | SWT.WRAP);
label2.setText("Drop Target for MyData[]");
DragSource source = new DragSource(label1, DND.DROP_COPY);
source.setTransfer(new Transfer[] { MyTransfer.getInstance() });
source.addDragListener(new DragSourceAdapter() {
public void dragSetData(DragSourceEvent event) {
MyType myType1 = new MyType();
myType1.fileName = "C:\\abc.txt";
myType1.fileLength = 1000;
myType1.lastModified = 12312313;
MyType myType2 = new MyType();
myType2.fileName = "C:\\xyz.txt";
myType2.fileLength = 500;
myType2.lastModified = 12312323;
event.data = new MyType[] { myType1, myType2 };
}
});
DropTarget target = new DropTarget(label2, DND.DROP_COPY
| DND.DROP_DEFAULT);
target.setTransfer(new Transfer[] { MyTransfer.getInstance() });
target.addDropListener(new DropTargetAdapter() {
public void dragEnter(DropTargetEvent event) {
if (event.detail == DND.DROP_DEFAULT) {
event.detail = DND.DROP_COPY;
}
}
public void dragOperationChanged(DropTargetEvent event) {
if (event.detail == DND.DROP_DEFAULT) {
event.detail = DND.DROP_COPY;
}
}
public void drop(DropTargetEvent event) {
if (event.data != null) {
MyType[] myTypes = (MyType[]) event.data;
if (myTypes != null) {
String string = "";
for (int i = 0; i < myTypes.length; i++) {
string += myTypes[i].fileName + " ";
}
label2.setText(string);
}
}
}
});
shell.setSize(200, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Drag and Drop example snippet: drag leaf items in a tree
/*
* Drag and Drop example snippet: drag leaf items in a tree
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class Snippet91 {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Tree tree = new Tree(shell, SWT.BORDER);
for (int i = 0; i < 3; i++) {
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText("item " + i);
for (int j = 0; j < 3; j++) {
TreeItem subItem = new TreeItem(item, SWT.NONE);
subItem.setText("item " + i + " " + j);
for (int k = 0; k < 3; k++) {
TreeItem subsubItem = new TreeItem(subItem, SWT.NONE);
subsubItem.setText("item " + i + " " + j + " " + k);
}
}
}
Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
int operations = DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
final DragSource source = new DragSource(tree, operations);
source.setTransfer(types);
final TreeItem[] dragSourceItem = new TreeItem[1];
source.addDragListener(new DragSourceListener() {
public void dragStart(DragSourceEvent event) {
TreeItem[] selection = tree.getSelection();
if (selection.length > 0 && selection[0].getItemCount() == 0) {
event.doit = true;
dragSourceItem[0] = selection[0];
} else {
event.doit = false;
}
};
public void dragSetData(DragSourceEvent event) {
event.data = dragSourceItem[0].getText();
}
public void dragFinished(DragSourceEvent event) {
if (event.detail == DND.DROP_MOVE)
dragSourceItem[0].dispose();
dragSourceItem[0] = null;
}
});
DropTarget target = new DropTarget(tree, operations);
target.setTransfer(types);
target.addDropListener(new DropTargetAdapter() {
public void dragOver(DropTargetEvent event) {
event.feedback = DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL;
if (event.item != null) {
TreeItem item = (TreeItem) event.item;
Point pt = display.map(null, tree, event.x, event.y);
Rectangle bounds = item.getBounds();
if (pt.y < bounds.y + bounds.height / 3) {
event.feedback |= DND.FEEDBACK_INSERT_BEFORE;
} else if (pt.y > bounds.y + 2 * bounds.height / 3) {
event.feedback |= DND.FEEDBACK_INSERT_AFTER;
} else {
event.feedback |= DND.FEEDBACK_SELECT;
}
}
}
public void drop(DropTargetEvent event) {
if (event.data == null) {
event.detail = DND.DROP_NONE;
return;
}
String text = (String) event.data;
if (event.item == null) {
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText(text);
} else {
TreeItem item = (TreeItem) event.item;
Point pt = display.map(null, tree, event.x, event.y);
Rectangle bounds = item.getBounds();
TreeItem parent = item.getParentItem();
if (parent != null) {
TreeItem[] items = parent.getItems();
int index = 0;
for (int i = 0; i < items.length; i++) {
if (items[i] == item) {
index = i;
break;
}
}
if (pt.y < bounds.y + bounds.height / 3) {
TreeItem newItem = new TreeItem(parent, SWT.NONE,
index);
newItem.setText(text);
} else if (pt.y > bounds.y + 2 * bounds.height / 3) {
TreeItem newItem = new TreeItem(parent, SWT.NONE,
index + 1);
newItem.setText(text);
} else {
TreeItem newItem = new TreeItem(item, SWT.NONE);
newItem.setText(text);
}
} else {
TreeItem[] items = tree.getItems();
int index = 0;
for (int i = 0; i < items.length; i++) {
if (items[i] == item) {
index = i;
break;
}
}
if (pt.y < bounds.y + bounds.height / 3) {
TreeItem newItem = new TreeItem(tree, SWT.NONE,
index);
newItem.setText(text);
} else if (pt.y > bounds.y + 2 * bounds.height / 3) {
TreeItem newItem = new TreeItem(tree, SWT.NONE,
index + 1);
newItem.setText(text);
} else {
TreeItem newItem = new TreeItem(item, SWT.NONE);
newItem.setText(text);
}
}
}
}
});
shell.setSize(400, 400);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Drag and Drop example snippet: drag text between two labels
/*
* Drag and Drop example snippet: drag text between two labels
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class Snippet78 {
public static void main(String[] args) {
Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Label label1 = new Label(shell, SWT.BORDER);
label1.setText("TEXT");
final Label label2 = new Label(shell, SWT.BORDER);
setDragDrop(label1);
setDragDrop(label2);
shell.setSize(200, 200);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public static void setDragDrop(final Label label) {
Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
int operations = DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
final DragSource source = new DragSource(label, operations);
source.setTransfer(types);
source.addDragListener(new DragSourceListener() {
public void dragStart(DragSourceEvent event) {
event.doit = (label.getText().length() != 0);
}
public void dragSetData(DragSourceEvent event) {
event.data = label.getText();
}
public void dragFinished(DragSourceEvent event) {
if (event.detail == DND.DROP_MOVE)
label.setText("");
}
});
DropTarget target = new DropTarget(label, operations);
target.setTransfer(types);
target.addDropListener(new DropTargetAdapter() {
public void drop(DropTargetEvent event) {
if (event.data == null) {
event.detail = DND.DROP_NONE;
return;
}
label.setText((String) event.data);
}
});
}
}
Illustrates dragging
//Send questions, comments, bug reports, etc. to the authors:
//Rob Warner (rwarner@interspatial.ru)
//Robert Harris (rbrt_harris@yahoo.ru)
import org.eclipse.swt.*;
import org.eclipse.swt.dnd.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
* This program illustrates dragging
*/
public class SnippetBoard {
/**
* Runs the application
*/
public void run() {
Display display = new Display();
Shell shell = new Shell(display);
createContents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private void createContents(Shell shell) {
shell.setLayout(new FillLayout());
Table table = new Table(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
// Create the types
Transfer[] types = new Transfer[] { TextTransfer.getInstance()};
// Create the drag source
DragSource source = new DragSource(table, DND.DROP_MOVE | DND.DROP_COPY);
source.setTransfer(types);
source.addDragListener(new DragSourceAdapter() {
public void dragSetData(DragSourceEvent event) {
// Get the selected items in the drag source
DragSource ds = (DragSource) event.widget;
Table table = (Table) ds.getControl();
TableItem[] selection = table.getSelection();
// Create a buffer to hold the selected items and fill it
StringBuffer buff = new StringBuffer();
for (int i = 0, n = selection.length; i < n; i++) {
buff.append(selection[i].getText());
}
// Put the data into the event
event.data = buff.toString();
}
});
// Create the drop target
DropTarget target = new DropTarget(table,
DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_DEFAULT);
target.setTransfer(types);
target.addDropListener(new DropTargetAdapter() {
public void dragEnter(DropTargetEvent event) {
if (event.detail == DND.DROP_DEFAULT) {
event.detail = (event.operations & DND.DROP_COPY) != 0 ? DND.DROP_COPY
: DND.DROP_NONE;
}
// Allow dropping text only
for (int i = 0, n = event.dataTypes.length; i < n; i++) {
if (TextTransfer.getInstance().isSupportedType(event.dataTypes[i])) {
event.currentDataType = event.dataTypes[i];
}
}
}
public void dragOver(DropTargetEvent event) {
// Provide visual feedback
event.feedback = DND.FEEDBACK_SELECT | DND.FEEDBACK_SCROLL;
}
public void drop(DropTargetEvent event) {
// If any text was dropped . . .
if (TextTransfer.getInstance().isSupportedType(event.currentDataType)) {
// Get the dropped data
DropTarget target = (DropTarget) event.widget;
Table table = (Table) target.getControl();
String data = (String) event.data;
// Create a new item in the table to hold the dropped data
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] { data});
table.redraw();
}
}
});
TableColumn column = new TableColumn(table, SWT.NONE);
// Seed the table
TableItem item = new TableItem(table, SWT.NONE);
item.setText(new String[] { "private static final int"});
item = new TableItem(table, SWT.NONE);
item.setText(new String[] { "String"});
item = new TableItem(table, SWT.BORDER);
item.setText(new String[] { "private static void main(String[] args) {"});
column.pack();
}
/**
* The application entry point
* @param args the command line arguments
*/
public static void main(String[] args) {
new SnippetBoard().run();
}
}
Simple DND (Drag and Drop) Example
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class SimpleDNDExample {
public static void main(String[] args) {
Shell shell = new Shell();
shell.setLayout(new FillLayout());
// Create the tree and some tree items
final Tree tree = new Tree(shell, SWT.NONE);
TreeItem item1 = new TreeItem(tree, SWT.NONE);
item1.setText("Item 1");
TreeItem item2 = new TreeItem(tree, SWT.NONE);
item2.setText("Item 2");
TreeItem item3 = new TreeItem(tree, SWT.NONE);
item3.setText("Item 3");
TreeItem item4 = new TreeItem(tree, SWT.NONE);
item4.setText("Item 4");
// Create the drag source on the tree
DragSource ds = new DragSource(tree, DND.DROP_MOVE);
ds.setTransfer(new Transfer[] { TextTransfer.getInstance() });
ds.addDragListener(new DragSourceAdapter() {
public void dragSetData(DragSourceEvent event) {
// Set the data to be the first selected item"s text
event.data = tree.getSelection()[0].getText();
}
});
// Create the button
final Button button = new Button(shell, SWT.FLAT);
button.setText("Button");
button.setAlignment(SWT.CENTER);
// Create the drop target on the button
DropTarget dt = new DropTarget(button, DND.DROP_MOVE);
dt.setTransfer(new Transfer[] { TextTransfer.getInstance() });
dt.addDropListener(new DropTargetAdapter() {
public void drop(DropTargetEvent event) {
// Set the buttons text to be the text being dropped
button.setText((String) event.data);
}
});
shell.pack();
shell.open();
Display display = Display.getDefault();
while (!shell.isDisposed())
if (!display.readAndDispatch())
display.sleep();
display.dispose();
}
}
SWT DnD (Drag and drop) Composite
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Text;
public class Ch12DnDComposite extends Composite {
public Ch12DnDComposite(Composite parent) {
super(parent, SWT.NONE);
FillLayout layout = new FillLayout();
setLayout(layout);
Text leftText = new Text(this, SWT.MULTI);
Text rightText = new Text(this, SWT.MULTI);
createDragSource(leftText);
createDragSource(rightText);
createDropTarget(leftText);
createDropTarget(rightText);
}
private void createDropTarget(final Text targetText) {
Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
DropTarget dropTarget = new DropTarget(targetText, DND.DROP_COPY);
dropTarget.setTransfer(types);
dropTarget.addDropListener(new DropTargetListener() {
public void dragEnter(DropTargetEvent event) {
}
public void dragLeave(DropTargetEvent event) {
}
public void dragOperationChanged(DropTargetEvent event) {
}
public void dragOver(DropTargetEvent event) {
}
public void drop(DropTargetEvent event) {
String data = (String) event.data;
targetText.append(data);
}
public void dropAccept(DropTargetEvent event) {
}
});
}
private void createDragSource(final Text sourceText) {
Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
DragSource dragSource = new DragSource(sourceText, DND.DROP_COPY);
dragSource.setTransfer(types);
dragSource.addDragListener(new DragSourceListener() {
public void dragStart(DragSourceEvent event) {
if (sourceText.getSelectionText().length() > 0) {
event.doit = true;
}
}
public void dragSetData(DragSourceEvent event) {
event.data = sourceText.getSelection();
}
public void dragFinished(DragSourceEvent event) {
//do nothing
}
});
}
}
SWT DND (Drag and Drop) comprehensive Example
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.HTMLTransfer;
import org.eclipse.swt.dnd.RTFTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.rubo;
import org.eclipse.swt.widgets.ruposite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
public class DNDExample {
private int dragOperation = 0;
private Transfer[] dragTypes = new Transfer[0];
private Control dragControl;
private int dragControlType = 0;
private DragSource dragSource;
private String dragDataText;
private String dragDataRTF;
private String dragDataHTML;
private String[] dragDataFiles;
private List fileList;
private boolean dragEnabled = false;
private int dropOperation = 0;
private int dropFeedback = 0;
private int dropDefaultOperation = 0;
private Transfer[] dropTypes = new Transfer[0];
private DropTarget dropTarget;
private Control dropControl;
private int dropControlType = 0;
private Composite defaultParent;
private boolean dropEnabled = false;
private Text dragConsole;
private boolean dragEventDetail = false;
private Text dropConsole;
private boolean dropEventDetail = false;
private static final int BUTTON_TOGGLE = 0;
private static final int BUTTON_RADIO = 1;
private static final int BUTTON_CHECK = 2;
private static final int CANVAS = 3;
private static final int LABEL = 4;
private static final int LIST = 5;
private static final int TABLE = 6;
private static final int TREE = 7;
private static final int TEXT = 8;
public static void main(String[] args) {
Display display = new Display();
DNDExample example = new DNDExample();
example.open(display);
display.dispose();
}
private void addDragTransfer(Transfer transfer) {
Transfer[] newTypes = new Transfer[dragTypes.length + 1];
System.arraycopy(dragTypes, 0, newTypes, 0, dragTypes.length);
newTypes[dragTypes.length] = transfer;
dragTypes = newTypes;
if (dragSource != null) {
dragSource.setTransfer(dragTypes);
}
}
private void addDropTransfer(Transfer transfer) {
Transfer[] newTypes = new Transfer[dropTypes.length + 1];
System.arraycopy(dropTypes, 0, newTypes, 0, dropTypes.length);
newTypes[dropTypes.length] = transfer;
dropTypes = newTypes;
if (dropTarget != null) {
dropTarget.setTransfer(dropTypes);
}
}
private void createDragOperations(Composite parent) {
parent.setLayout(new RowLayout(SWT.VERTICAL));
final Button moveButton = new Button(parent, SWT.CHECK);
moveButton.setText("DND.DROP_MOVE");
moveButton.setSelection(true);
dragOperation = DND.DROP_MOVE;
moveButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dragOperation |= DND.DROP_MOVE;
} else {
dragOperation = dragOperation & ~DND.DROP_MOVE;
if (dragOperation == 0) {
dragOperation = DND.DROP_MOVE;
moveButton.setSelection(true);
}
}
if (dragEnabled) {
createDragSource();
}
}
});
Button b = new Button(parent, SWT.CHECK);
b.setText("DND.DROP_COPY");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dragOperation |= DND.DROP_COPY;
} else {
dragOperation = dragOperation & ~DND.DROP_COPY;
if (dragOperation == 0) {
dragOperation = DND.DROP_MOVE;
moveButton.setSelection(true);
}
}
if (dragEnabled) {
createDragSource();
}
}
});
b = new Button(parent, SWT.CHECK);
b.setText("DND.DROP_LINK");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dragOperation |= DND.DROP_LINK;
} else {
dragOperation = dragOperation & ~DND.DROP_LINK;
if (dragOperation == 0) {
dragOperation = DND.DROP_MOVE;
moveButton.setSelection(true);
}
}
if (dragEnabled) {
createDragSource();
}
}
});
}
private void createDragSource() {
if (dragSource != null)
dragSource.dispose();
dragSource = new DragSource(dragControl, dragOperation);
dragSource.setTransfer(dragTypes);
dragSource.addDragListener(new DragSourceListener() {
public void dragFinished(org.eclipse.swt.dnd.DragSourceEvent event) {
dragConsole.append(">>dragFinished\n");
printEvent(event);
dragDataText = dragDataRTF = dragDataHTML = null;
dragDataFiles = null;
if (event.detail == DND.DROP_MOVE) {
switch (dragControlType) {
case BUTTON_CHECK:
case BUTTON_TOGGLE:
case BUTTON_RADIO: {
Button b = (Button) dragControl;
b.setText("");
break;
}
case TABLE: {
Table table = (Table) dragControl;
TableItem[] items = table.getSelection();
for (int i = 0; i < items.length; i++) {
items[i].dispose();
}
break;
}
case TEXT: {
Text text = (Text) dragControl;
text.clearSelection();
break;
}
case TREE: {
Tree tree = (Tree) dragControl;
TreeItem[] items = tree.getSelection();
for (int i = 0; i < items.length; i++) {
items[i].dispose();
}
break;
}
case CANVAS: {
dragControl.setData("STRINGS", null);
dragControl.redraw();
break;
}
case LABEL: {
Label label = (Label) dragControl;
label.setText("");
break;
}
case LIST: {
List list = (List) dragControl;
int[] indices = list.getSelectionIndices();
list.remove(indices);
break;
}
}
}
}
public void dragSetData(org.eclipse.swt.dnd.DragSourceEvent event) {
dragConsole.append(">>dragSetData\n");
printEvent(event);
if (TextTransfer.getInstance().isSupportedType(event.dataType)) {
event.data = dragDataText;
}
if (RTFTransfer.getInstance().isSupportedType(event.dataType)) {
event.data = dragDataRTF;
}
if (HTMLTransfer.getInstance().isSupportedType(event.dataType)) {
event.data = dragDataHTML;
}
if (FileTransfer.getInstance().isSupportedType(event.dataType)) {
event.data = dragDataFiles;
}
}
public void dragStart(org.eclipse.swt.dnd.DragSourceEvent event) {
dragConsole.append(">>dragStart\n");
printEvent(event);
dragDataFiles = fileList.getItems();
switch (dragControlType) {
case BUTTON_CHECK:
case BUTTON_TOGGLE:
case BUTTON_RADIO: {
Button b = (Button) dragControl;
dragDataText = b.getSelection() ? "true" : "false";
break;
}
case TABLE: {
Table table = (Table) dragControl;
TableItem[] items = table.getSelection();
if (items.length == 0) {
event.doit = false;
} else {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < items.length; i++) {
buffer.append(items[i].getText());
if (items.length > 1 && i < items.length - 1) {
buffer.append("\n");
}
}
dragDataText = buffer.toString();
}
break;
}
case TEXT: {
Text text = (Text) dragControl;
String s = text.getSelectionText();
if (s.length() == 0) {
event.doit = false;
} else {
dragDataText = s;
}
break;
}
case TREE: {
Tree tree = (Tree) dragControl;
TreeItem[] items = tree.getSelection();
if (items.length == 0) {
event.doit = false;
} else {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < items.length; i++) {
buffer.append(items[i].getText());
if (items.length > 1 && i < items.length - 1) {
buffer.append("\n");
}
}
dragDataText = buffer.toString();
}
break;
}
case CANVAS: {
String[] strings = (String[]) dragControl
.getData("STRINGS");
if (strings == null || strings.length == 0) {
event.doit = false;
} else {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < strings.length; i++) {
buffer.append(strings[i]);
if (strings.length > 1 && i < strings.length - 1) {
buffer.append("\n");
}
}
dragDataText = buffer.toString();
}
break;
}
case LABEL: {
Label label = (Label) dragControl;
String string = label.getText();
if (string.length() == 0) {
event.doit = false;
} else {
dragDataText = string;
}
break;
}
case LIST: {
List list = (List) dragControl;
String[] selection = list.getSelection();
if (selection.length == 0) {
event.doit = false;
} else {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < selection.length; i++) {
buffer.append(selection[i]);
if (selection.length > 1
&& i < selection.length - 1) {
buffer.append("\n");
}
}
dragDataText = buffer.toString();
}
break;
}
default:
throw new SWTError(SWT.ERROR_NOT_IMPLEMENTED);
}
if (dragDataText != null) {
dragDataRTF = "{\\rtf1{\\colortbl;\\red255\\green0\\blue0;}\\cf1\\b "
+ dragDataText + "}";
dragDataHTML = "<b>" + dragDataText + "</b>";
}
for (int i = 0; i < dragTypes.length; i++) {
if (dragTypes[i] instanceof TextTransfer
&& dragDataText == null) {
event.doit = false;
}
if (dragTypes[i] instanceof RTFTransfer
&& dragDataRTF == null) {
event.doit = false;
}
if (dragTypes[i] instanceof HTMLTransfer
&& dragDataHTML == null) {
event.doit = false;
}
if (dragTypes[i] instanceof FileTransfer
&& (dragDataFiles == null || dragDataFiles.length == 0)) {
event.doit = false;
}
}
}
});
}
private void createDragTypes(Composite parent) {
parent.setLayout(new GridLayout());
Button b = new Button(parent, SWT.CHECK);
b.setText("Text Transfer");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
addDragTransfer(TextTransfer.getInstance());
} else {
removeDragTransfer(TextTransfer.getInstance());
}
}
});
b = new Button(parent, SWT.CHECK);
b.setText("RTF Transfer");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
addDragTransfer(RTFTransfer.getInstance());
} else {
removeDragTransfer(RTFTransfer.getInstance());
}
}
});
b = new Button(parent, SWT.CHECK);
b.setText("HTML Transfer");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
addDragTransfer(HTMLTransfer.getInstance());
} else {
removeDragTransfer(HTMLTransfer.getInstance());
}
}
});
b = new Button(parent, SWT.CHECK);
b.setText("File Transfer");
b.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
addDragTransfer(FileTransfer.getInstance());
} else {
removeDragTransfer(FileTransfer.getInstance());
}
}
});
b = new Button(parent, SWT.PUSH);
b.setText("Select File(s)");
b.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(fileList.getShell(),
SWT.OPEN | SWT.MULTI);
String result = dialog.open();
if (result != null && result.length() > 0) {
fileList.removeAll();
String separator = System.getProperty("file.separator");
String path = dialog.getFilterPath();
String[] names = dialog.getFileNames();
for (int i = 0; i < names.length; i++) {
fileList.add(path + separator + names[i]);
}
}
}
});
fileList = new List(parent, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
GridData data = new GridData();
data.grabExcessHorizontalSpace = true;
data.horizontalAlignment = GridData.FILL;
data.verticalAlignment = GridData.BEGINNING;
fileList.setLayoutData(data);
}
private void createDragWidget(Composite parent) {
parent.setLayout(new FormLayout());
Combo combo = new Combo(parent, SWT.READ_ONLY);
combo.setItems(new String[] { "Toggle Button", "Radio Button",
"Checkbox", "Canvas", "Label", "List", "Table", "Tree" });
combo.select(LABEL);
dragControlType = combo.getSelectionIndex();
dragControl = createWidget(dragControlType, parent, "Drag Source");
combo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Object data = dragControl.getLayoutData();
Composite parent = dragControl.getParent();
dragControl.dispose();
Combo c = (Combo) e.widget;
dragControlType = c.getSelectionIndex();
dragControl = createWidget(dragControlType, parent,
"Drag Source");
dragControl.setLayoutData(data);
if (dragEnabled)
createDragSource();
parent.layout();
}
});
Button b = new Button(parent, SWT.CHECK);
b.setText("DragSource");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
dragEnabled = b.getSelection();
if (dragEnabled) {
createDragSource();
} else {
if (dragSource != null) {
dragSource.dispose();
}
dragSource = null;
}
}
});
FormData data = new FormData();
data.top = new FormAttachment(0, 10);
data.bottom = new FormAttachment(combo, -10);
data.left = new FormAttachment(0, 10);
data.right = new FormAttachment(100, -10);
dragControl.setLayoutData(data);
data = new FormData();
data.bottom = new FormAttachment(100, -10);
data.left = new FormAttachment(0, 10);
combo.setLayoutData(data);
data = new FormData();
data.bottom = new FormAttachment(100, -10);
data.left = new FormAttachment(combo, 10);
b.setLayoutData(data);
}
private void createDropOperations(Composite parent) {
parent.setLayout(new RowLayout(SWT.VERTICAL));
final Button moveButton = new Button(parent, SWT.CHECK);
moveButton.setText("DND.DROP_MOVE");
moveButton.setSelection(true);
dropOperation = DND.DROP_MOVE;
moveButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropOperation |= DND.DROP_MOVE;
} else {
dropOperation = dropOperation & ~DND.DROP_MOVE;
if (dropOperation == 0
|| (dropDefaultOperation & DND.DROP_MOVE) != 0) {
dropOperation |= DND.DROP_MOVE;
moveButton.setSelection(true);
}
}
if (dropEnabled) {
createDropTarget();
}
}
});
final Button copyButton = new Button(parent, SWT.CHECK);
copyButton.setText("DND.DROP_COPY");
copyButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropOperation |= DND.DROP_COPY;
} else {
dropOperation = dropOperation & ~DND.DROP_COPY;
if (dropOperation == 0
|| (dropDefaultOperation & DND.DROP_COPY) != 0) {
dropOperation = DND.DROP_COPY;
copyButton.setSelection(true);
}
}
if (dropEnabled) {
createDropTarget();
}
}
});
final Button linkButton = new Button(parent, SWT.CHECK);
linkButton.setText("DND.DROP_LINK");
linkButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropOperation |= DND.DROP_LINK;
} else {
dropOperation = dropOperation & ~DND.DROP_LINK;
if (dropOperation == 0
|| (dropDefaultOperation & DND.DROP_LINK) != 0) {
dropOperation = DND.DROP_LINK;
linkButton.setSelection(true);
}
}
if (dropEnabled) {
createDropTarget();
}
}
});
Button b = new Button(parent, SWT.CHECK);
b.setText("DND.DROP_DEFAULT");
defaultParent = new Composite(parent, SWT.NONE);
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropOperation |= DND.DROP_DEFAULT;
defaultParent.setVisible(true);
} else {
dropOperation = dropOperation & ~DND.DROP_DEFAULT;
defaultParent.setVisible(false);
}
if (dropEnabled) {
createDropTarget();
}
}
});
defaultParent.setVisible(false);
GridLayout layout = new GridLayout();
layout.marginWidth = 20;
defaultParent.setLayout(layout);
Label label = new Label(defaultParent, SWT.NONE);
label.setText("Value for default operation is:");
b = new Button(defaultParent, SWT.RADIO);
b.setText("DND.DROP_MOVE");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropDefaultOperation = DND.DROP_MOVE;
dropOperation |= DND.DROP_MOVE;
moveButton.setSelection(true);
if (dropEnabled) {
createDropTarget();
}
}
}
});
b = new Button(defaultParent, SWT.RADIO);
b.setText("DND.DROP_COPY");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropDefaultOperation = DND.DROP_COPY;
dropOperation |= DND.DROP_COPY;
copyButton.setSelection(true);
if (dropEnabled) {
createDropTarget();
}
}
}
});
b = new Button(defaultParent, SWT.RADIO);
b.setText("DND.DROP_LINK");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropDefaultOperation = DND.DROP_LINK;
dropOperation |= DND.DROP_LINK;
linkButton.setSelection(true);
if (dropEnabled) {
createDropTarget();
}
}
}
});
b = new Button(defaultParent, SWT.RADIO);
b.setText("DND.DROP_NONE");
b.setSelection(true);
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropDefaultOperation = DND.DROP_NONE;
dropOperation &= ~DND.DROP_DEFAULT;
if (dropEnabled) {
createDropTarget();
}
}
}
});
}
private void createDropTarget() {
if (dropTarget != null)
dropTarget.dispose();
dropTarget = new DropTarget(dropControl, dropOperation);
dropTarget.setTransfer(dropTypes);
dropTarget.addDropListener(new DropTargetListener() {
public void dragEnter(DropTargetEvent event) {
dropConsole.append(">>dragEnter\n");
printEvent(event);
if (event.detail == DND.DROP_DEFAULT) {
event.detail = dropDefaultOperation;
}
event.feedback = dropFeedback;
}
public void dragLeave(DropTargetEvent event) {
dropConsole.append(">>dragLeave\n");
printEvent(event);
}
public void dragOperationChanged(DropTargetEvent event) {
dropConsole.append(">>dragOperationChanged\n");
printEvent(event);
if (event.detail == DND.DROP_DEFAULT) {
event.detail = dropDefaultOperation;
}
event.feedback = dropFeedback;
}
public void dragOver(DropTargetEvent event) {
dropConsole.append(">>dragOver\n");
printEvent(event);
event.feedback = dropFeedback;
}
public void drop(DropTargetEvent event) {
dropConsole.append(">>drop\n");
printEvent(event);
String[] strings = null;
if (TextTransfer.getInstance().isSupportedType(
event.currentDataType)
|| RTFTransfer.getInstance().isSupportedType(
event.currentDataType)
|| HTMLTransfer.getInstance().isSupportedType(
event.currentDataType)) {
strings = new String[] { (String) event.data };
}
if (FileTransfer.getInstance().isSupportedType(
event.currentDataType)) {
strings = (String[]) event.data;
}
if (strings == null || strings.length == 0) {
dropConsole.append("!!Invalid data dropped");
return;
}
if (strings.length == 1
&& (dropControlType == TABLE || dropControlType == TREE || dropControlType == LIST)) {
// convert string separated by "\n" into an array of strings
String string = strings[0];
int count = 0;
int offset = string.indexOf("\n", 0);
while (offset > 0) {
count++;
offset = string.indexOf("\n", offset + 1);
}
if (count > 0) {
strings = new String[count + 1];
int start = 0;
int end = string.indexOf("\n");
int index = 0;
while (start < end) {
strings[index++] = string.substring(start, end);
start = end + 1;
end = string.indexOf("\n", start);
if (end == -1)
end = string.length();
}
}
}
switch (dropControlType) {
case BUTTON_CHECK:
case BUTTON_TOGGLE:
case BUTTON_RADIO: {
Button b = (Button) dropControl;
b.setText(strings[0]);
break;
}
case TABLE: {
Table table = (Table) dropControl;
Point p = event.display.map(null, table, event.x, event.y);
TableItem dropItem = table.getItem(p);
int index = dropItem == null ? table.getItemCount() : table
.indexOf(dropItem);
for (int i = 0; i < strings.length; i++) {
TableItem item = new TableItem(table, SWT.NONE, index);
item.setText(0, strings[i]);
item.setText(1, "dropped item");
}
TableColumn[] columns = table.getColumns();
for (int i = 0; i < columns.length; i++) {
columns[i].pack();
}
break;
}
case TEXT: {
Text text = (Text) dropControl;
for (int i = 0; i < strings.length; i++) {
text.append(strings[i] + "\n");
}
break;
}
case TREE: {
Tree tree = (Tree) dropControl;
Point p = event.display.map(null, tree, event.x, event.y);
TreeItem parentItem = tree.getItem(p);
for (int i = 0; i < strings.length; i++) {
TreeItem item = parentItem != null ? new TreeItem(
parentItem, SWT.NONE) : new TreeItem(tree,
SWT.NONE);
item.setText(strings[i]);
}
break;
}
case CANVAS: {
dropControl.setData("STRINGS", strings);
dropControl.redraw();
break;
}
case LABEL: {
Label label = (Label) dropControl;
label.setText(strings[0]);
break;
}
case LIST: {
List list = (List) dropControl;
for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
break;
}
default:
throw new SWTError(SWT.ERROR_NOT_IMPLEMENTED);
}
}
public void dropAccept(DropTargetEvent event) {
dropConsole.append(">>dropAccept\n");
printEvent(event);
}
});
}
private void createFeedbackTypes(Group parent) {
parent.setLayout(new RowLayout(SWT.VERTICAL));
Button b = new Button(parent, SWT.CHECK);
b.setText("FEEDBACK_SELECT");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropFeedback |= DND.FEEDBACK_SELECT;
} else {
dropFeedback &= ~DND.FEEDBACK_SELECT;
}
}
});
b = new Button(parent, SWT.CHECK);
b.setText("FEEDBACK_SCROLL");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropFeedback |= DND.FEEDBACK_SCROLL;
} else {
dropFeedback &= ~DND.FEEDBACK_SCROLL;
}
}
});
b = new Button(parent, SWT.CHECK);
b.setText("FEEDBACK_INSERT_BEFORE");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropFeedback |= DND.FEEDBACK_INSERT_BEFORE;
} else {
dropFeedback &= ~DND.FEEDBACK_INSERT_BEFORE;
}
}
});
b = new Button(parent, SWT.CHECK);
b.setText("FEEDBACK_INSERT_AFTER");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropFeedback |= DND.FEEDBACK_INSERT_AFTER;
} else {
dropFeedback &= ~DND.FEEDBACK_INSERT_AFTER;
}
}
});
b = new Button(parent, SWT.CHECK);
b.setText("FEEDBACK_EXPAND");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
dropFeedback |= DND.FEEDBACK_EXPAND;
} else {
dropFeedback &= ~DND.FEEDBACK_EXPAND;
}
}
});
}
private void createDropTypes(Composite parent) {
parent.setLayout(new RowLayout(SWT.VERTICAL));
Button b = new Button(parent, SWT.CHECK);
b.setText("Text Transfer");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
addDropTransfer(TextTransfer.getInstance());
} else {
removeDropTransfer(TextTransfer.getInstance());
}
}
});
b = new Button(parent, SWT.CHECK);
b.setText("RTF Transfer");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
addDropTransfer(RTFTransfer.getInstance());
} else {
removeDropTransfer(RTFTransfer.getInstance());
}
}
});
b = new Button(parent, SWT.CHECK);
b.setText("HTML Transfer");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
addDropTransfer(HTMLTransfer.getInstance());
} else {
removeDropTransfer(HTMLTransfer.getInstance());
}
}
});
b = new Button(parent, SWT.CHECK);
b.setText("File Transfer");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
if (b.getSelection()) {
addDropTransfer(FileTransfer.getInstance());
} else {
removeDropTransfer(FileTransfer.getInstance());
}
}
});
}
private void createDropWidget(Composite parent) {
parent.setLayout(new FormLayout());
Combo combo = new Combo(parent, SWT.READ_ONLY);
combo
.setItems(new String[] { "Toggle Button", "Radio Button",
"Checkbox", "Canvas", "Label", "List", "Table", "Tree",
"Text" });
combo.select(LABEL);
dropControlType = combo.getSelectionIndex();
dropControl = createWidget(dropControlType, parent, "Drop Target");
combo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Object data = dropControl.getLayoutData();
Composite parent = dropControl.getParent();
dropControl.dispose();
Combo c = (Combo) e.widget;
dropControlType = c.getSelectionIndex();
dropControl = createWidget(dropControlType, parent,
"Drop Target");
dropControl.setLayoutData(data);
if (dropEnabled)
createDropTarget();
parent.layout();
}
});
Button b = new Button(parent, SWT.CHECK);
b.setText("DropTarget");
b.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Button b = (Button) e.widget;
dropEnabled = b.getSelection();
if (dropEnabled) {
createDropTarget();
} else {
if (dropTarget != null) {
dropTarget.dispose();
}
dropTarget = null;
}
}
});
FormData data = new FormData();
data.top = new FormAttachment(0, 10);
data.bottom = new FormAttachment(combo, -10);
data.left = new FormAttachment(0, 10);
data.right = new FormAttachment(100, -10);
dropControl.setLayoutData(data);
data = new FormData();
data.bottom = new FormAttachment(100, -10);
data.left = new FormAttachment(0, 10);
combo.setLayoutData(data);
data = new FormData();
data.bottom = new FormAttachment(100, -10);
data.left = new FormAttachment(combo, 10);
b.setLayoutData(data);
}
private Control createWidget(int type, Composite parent, String prefix) {
switch (type) {
case BUTTON_CHECK: {
Button button = new Button(parent, SWT.CHECK);
button.setText(prefix + " Check box");
return button;
}
case BUTTON_TOGGLE: {
Button button = new Button(parent, SWT.TOGGLE);
button.setText(prefix + " Toggle button");
return button;
}
case BUTTON_RADIO: {
Button button = new Button(parent, SWT.RADIO);
button.setText(prefix + " Radio button");
return button;
}
case TABLE: {
Table table = new Table(parent, SWT.BORDER | SWT.MULTI);
TableColumn column1 = new TableColumn(table, SWT.NONE);
TableColumn column2 = new TableColumn(table, SWT.NONE);
for (int i = 0; i < 10; i++) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(0, prefix + " name " + i);
item.setText(1, prefix + " value " + i);
}
column1.pack();
column2.pack();
return table;
}
case TEXT: {
Text text = new Text(parent, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL
| SWT.H_SCROLL);
text.setText(prefix + " Text");
return text;
}
case TREE: {
Tree tree = new Tree(parent, SWT.BORDER);
for (int i = 0; i < 3; i++) {
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText(prefix + " item " + i);
for (int j = 0; j < 3; j++) {
TreeItem subItem = new TreeItem(item, SWT.NONE);
subItem.setText(prefix + " item " + j);
for (int k = 0; k < 3; k++) {
TreeItem subsubItem = new TreeItem(subItem, SWT.NONE);
subsubItem.setText(prefix + " item " + k);
}
}
}
return tree;
}
case CANVAS: {
Canvas canvas = new Canvas(parent, SWT.BORDER);
canvas.setData("STRINGS",
new String[] { prefix + " Canvas widget" });
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
Canvas c = (Canvas) e.widget;
Image image = (Image) c.getData("IMAGE");
if (image != null) {
e.gc.drawImage(image, 5, 5);
} else {
String[] strings = (String[]) c.getData("STRINGS");
if (strings != null) {
FontMetrics metrics = e.gc.getFontMetrics();
int height = metrics.getHeight();
int y = 5;
for (int i = 0; i < strings.length; i++) {
e.gc.drawString(strings[i], 5, y);
y += height + 5;
}
}
}
}
});
return canvas;
}
case LABEL: {
Label label = new Label(parent, SWT.BORDER);
label.setText(prefix + " Label");
return label;
}
case LIST: {
List list = new List(parent, SWT.BORDER);
list
.setItems(new String[] { prefix + " Item a",
prefix + " Item b", prefix + " Item c",
prefix + " Item d" });
return list;
}
default:
throw new SWTError(SWT.ERROR_NOT_IMPLEMENTED);
}
}
public void open(Display display) {
Shell shell = new Shell(display);
shell.setText("Drag and Drop Example");
shell.setLayout(new FillLayout());
ScrolledComposite sc = new ScrolledComposite(shell, SWT.H_SCROLL
| SWT.V_SCROLL);
Composite parent = new Composite(sc, SWT.NONE);
sc.setContent(parent);
parent.setLayout(new FormLayout());
Label dragLabel = new Label(parent, SWT.LEFT);
dragLabel.setText("Drag Source:");
Group dragWidgetGroup = new Group(parent, SWT.NONE);
dragWidgetGroup.setText("Widget");
createDragWidget(dragWidgetGroup);
Composite cLeft = new Composite(parent, SWT.NONE);
cLeft.setLayout(new GridLayout(2, false));
Group dragOperationsGroup = new Group(cLeft, SWT.NONE);
dragOperationsGroup.setLayoutData(new GridData(SWT.LEFT, SWT.FILL,
false, false, 1, 1));
dragOperationsGroup.setText("Allowed Operation(s):");
createDragOperations(dragOperationsGroup);
Group dragTypesGroup = new Group(cLeft, SWT.NONE);
dragTypesGroup.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true,
false, 1, 1));
dragTypesGroup.setText("Transfer Type(s):");
createDragTypes(dragTypesGroup);
dragConsole = new Text(cLeft, SWT.READ_ONLY | SWT.BORDER | SWT.V_SCROLL
| SWT.H_SCROLL | SWT.MULTI);
dragConsole.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,
2, 1));
Menu menu = new Menu(shell, SWT.POP_UP);
MenuItem item = new MenuItem(menu, SWT.PUSH);
item.setText("Clear");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
dragConsole.setText("");
}
});
item = new MenuItem(menu, SWT.CHECK);
item.setText("Show Event detail");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
MenuItem item = (MenuItem) e.widget;
dragEventDetail = item.getSelection();
}
});
dragConsole.setMenu(menu);
Label dropLabel = new Label(parent, SWT.LEFT);
dropLabel.setText("Drop Target:");
Group dropWidgetGroup = new Group(parent, SWT.NONE);
dropWidgetGroup.setText("Widget");
createDropWidget(dropWidgetGroup);
Composite cRight = new Composite(parent, SWT.NONE);
cRight.setLayout(new GridLayout(2, false));
Group dropOperationsGroup = new Group(cRight, SWT.NONE);
dropOperationsGroup.setLayoutData(new GridData(SWT.LEFT, SWT.FILL,
false, false, 1, 2));
dropOperationsGroup.setText("Allowed Operation(s):");
createDropOperations(dropOperationsGroup);
Group dropTypesGroup = new Group(cRight, SWT.NONE);
dropTypesGroup.setText("Transfer Type(s):");
createDropTypes(dropTypesGroup);
Group feedbackTypesGroup = new Group(cRight, SWT.NONE);
feedbackTypesGroup.setText("Feedback Type(s):");
createFeedbackTypes(feedbackTypesGroup);
dropConsole = new Text(cRight, SWT.READ_ONLY | SWT.BORDER
| SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI);
dropConsole.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,
2, 1));
menu = new Menu(shell, SWT.POP_UP);
item = new MenuItem(menu, SWT.PUSH);
item.setText("Clear");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
dropConsole.setText("");
}
});
item = new MenuItem(menu, SWT.CHECK);
item.setText("Show Event detail");
item.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
MenuItem item = (MenuItem) e.widget;
dropEventDetail = item.getSelection();
}
});
dropConsole.setMenu(menu);
int height = 200;
FormData data = new FormData();
data.top = new FormAttachment(0, 10);
data.left = new FormAttachment(0, 10);
dragLabel.setLayoutData(data);
data = new FormData();
data.top = new FormAttachment(dragLabel, 10);
data.left = new FormAttachment(0, 10);
data.right = new FormAttachment(50, -10);
data.height = height;
dragWidgetGroup.setLayoutData(data);
data = new FormData();
data.top = new FormAttachment(dragWidgetGroup, 10);
data.left = new FormAttachment(0, 10);
data.right = new FormAttachment(50, -10);
data.bottom = new FormAttachment(100, -10);
cLeft.setLayoutData(data);
data = new FormData();
data.top = new FormAttachment(0, 10);
data.left = new FormAttachment(cLeft, 10);
dropLabel.setLayoutData(data);
data = new FormData();
data.top = new FormAttachment(dropLabel, 10);
data.left = new FormAttachment(cLeft, 10);
data.right = new FormAttachment(100, -10);
data.height = height;
dropWidgetGroup.setLayoutData(data);
data = new FormData();
data.top = new FormAttachment(dropWidgetGroup, 10);
data.left = new FormAttachment(cLeft, 10);
data.right = new FormAttachment(100, -10);
data.bottom = new FormAttachment(100, -10);
cRight.setLayoutData(data);
sc.setMinSize(parent.ruputeSize(SWT.DEFAULT, SWT.DEFAULT));
sc.setExpandHorizontal(true);
sc.setExpandVertical(true);
Point size = shell.ruputeSize(SWT.DEFAULT, SWT.DEFAULT);
Rectangle monitorArea = shell.getMonitor().getClientArea();
shell.setSize(Math.min(size.x, monitorArea.width - 20), Math.min(
size.y, monitorArea.height - 20));
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
private void printEvent(DragSourceEvent e) {
if (!dragEventDetail)
return;
StringBuffer sb = new StringBuffer();
sb.append("widget: ");
sb.append(e.widget);
sb.append(", time: ");
sb.append(e.time);
sb.append(", operation: ");
sb.append(e.detail);
sb.append(", type: ");
sb.append(e.dataType != null ? e.dataType.type : 0);
sb.append(", doit: ");
sb.append(e.doit);
sb.append(", data: ");
sb.append(e.data);
sb.append("\n");
dragConsole.append(sb.toString());
}
private void printEvent(DropTargetEvent e) {
if (!dropEventDetail)
return;
StringBuffer sb = new StringBuffer();
sb.append("widget; ");
sb.append(e.widget);
sb.append(", time: ");
sb.append(e.time);
sb.append(", x: ");
sb.append(e.x);
sb.append(", y: ");
sb.append(e.y);
sb.append(", item: ");
sb.append(e.item);
sb.append(", operations: ");
sb.append(e.operations);
sb.append(", operation: ");
sb.append(e.detail);
sb.append(", feedback: ");
sb.append(e.feedback);
if (e.dataTypes != null) {
for (int i = 0; i < e.dataTypes.length; i++) {
sb.append(", dataType ");
sb.append(i);
sb.append(": ");
sb.append(e.dataTypes[i].type);
}
} else {
sb.append(", dataTypes: none");
}
sb.append(", currentDataType: ");
sb.append(e.currentDataType);
sb.append(", data: ");
sb.append(e.data);
sb.append("\n");
dropConsole.append(sb.toString());
}
private void removeDragTransfer(Transfer transfer) {
if (dragTypes.length == 1) {
dragTypes = new Transfer[0];
} else {
int index = -1;
for (int i = 0; i < dragTypes.length; i++) {
if (dragTypes[i] == transfer) {
index = i;
break;
}
}
if (index == -1)
return;
Transfer[] newTypes = new Transfer[dragTypes.length - 1];
System.arraycopy(dragTypes, 0, newTypes, 0, index);
System.arraycopy(dragTypes, index + 1, newTypes, index,
dragTypes.length - index - 1);
dragTypes = newTypes;
}
if (dragSource != null) {
dragSource.setTransfer(dragTypes);
}
}
private void removeDropTransfer(Transfer transfer) {
if (dropTypes.length == 1) {
dropTypes = new Transfer[0];
} else {
int index = -1;
for (int i = 0; i < dropTypes.length; i++) {
if (dropTypes[i] == transfer) {
index = i;
break;
}
}
if (index == -1)
return;
Transfer[] newTypes = new Transfer[dropTypes.length - 1];
System.arraycopy(dropTypes, 0, newTypes, 0, index);
System.arraycopy(dropTypes, index + 1, newTypes, index,
dropTypes.length - index - 1);
dropTypes = newTypes;
}
if (dropTarget != null) {
dropTarget.setTransfer(dropTypes);
}
}
}
Word Jumbles
/*******************************************************************************
* All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
*
* Created on 2004-4-26 15:46:26 by JACK $Id$
*
******************************************************************************/
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
public class WordJumbles {
Display display = new Display();
Shell shell = new Shell(display);
String word;
Label[] labelsRowOne;
Label[] labelsRowTwo;
Font font = new Font(display, "Arial", 18, SWT.BOLD);
public void setDragSource(final Label label) {
// Allows text to be moved only.
int operations = DND.DROP_MOVE;
final DragSource dragSource = new DragSource(label, operations);
// Data should be transfered in plain text format.
Transfer[] formats = new Transfer[] { TextTransfer.getInstance()};
dragSource.setTransfer(formats);
dragSource.addDragListener(new DragSourceListener() {
public void dragStart(DragSourceEvent event) {
// Disallows drags if text is not available.
if (label.getText().length() == 0)
event.doit = false;
}
public void dragSetData(DragSourceEvent event) {
// Provides the text data.
if (TextTransfer.getInstance().isSupportedType(event.dataType))
event.data = label.getText();
}
public void dragFinished(DragSourceEvent event) {
// Removes the text after the move operation.
if (event.doit == true || event.detail == DND.DROP_MOVE) {
label.setText("");
}
}
});
label.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
dragSource.dispose();
}
});
}
public void setDropTarget(final Label label) {
int operations = DND.DROP_MOVE;
final DropTarget dropTarget = new DropTarget(label, operations);
// Data should be transfered in plain text format.
Transfer[] formats = new Transfer[] { TextTransfer.getInstance()};
dropTarget.setTransfer(formats);
dropTarget.addDropListener(new DropTargetListener() {
public void dragEnter(DropTargetEvent event) {
// Does not accept any drop if the label has text on it.
if(label.getText().length() != 0)
event.detail = DND.DROP_NONE;
}
public void dragLeave(DropTargetEvent event) {
}
public void dragOperationChanged(DropTargetEvent event) {
}
public void dragOver(DropTargetEvent event) {
}
public void drop(DropTargetEvent event) {
if (TextTransfer
.getInstance()
.isSupportedType(event.currentDataType)) {
String text = (String) event.data;
label.setText(text);
// Checks the result.
check();
}
}
public void dropAccept(DropTargetEvent event) {
}
});
label.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
dropTarget.dispose();
}
});
}
private void check() {
for(int i=0; i<word.length(); i++) {
if(! labelsRowTwo[i].getText().equals(word.charAt(i) + ""))
return;
}
MessageBox messageBox = new MessageBox(shell);
messageBox.setMessage("Success!");
messageBox.open();
}
public WordJumbles(String word) {
this.word = word;
shell.setText("Word Jumbles");
labelsRowOne = new Label[word.length()];
labelsRowTwo = new Label[word.length()];
int width = 40;
// In the production version, you need to implement random permutation
// generation.
// Apache Jakarta Commons provides this function, see
// org.apache.rumons.math.random.RandomDataImpl
int[] randomPermutation = { 5, 2, 6, 3, 1, 4, 0 };
for (int i = 0; i < word.length(); i++) {
final Label labelRowOne = new Label(shell, SWT.BORDER);
labelsRowOne[i] = labelRowOne;
labelRowOne.setBounds(10 + width * i, 10, width - 5, width - 5);
labelRowOne.setFont(font);
labelRowOne.setText(word.charAt(randomPermutation[i]) + "");
labelRowOne.setAlignment(SWT.CENTER);
setDragSource(labelRowOne);
//setDropTarget(labelRowOne);
final Label labelRowTwo = new Label(shell, SWT.BORDER);
labelsRowTwo[i] = labelRowTwo;
labelRowTwo.setBounds(
10 + width * i,
20 + width,
width - 5,
width - 5);
labelRowTwo.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
labelRowTwo.setFont(font);
labelRowTwo.setAlignment(SWT.CENTER);
setDragSource(labelRowTwo);
//setDropTarget(labelRowTwo);
}
shell.pack();
shell.open();
//textUser.forceFocus();
// Set up the event loop.
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
// If no more entries in event queue
display.sleep();
}
}
display.dispose();
}
public static void main(String[] args) {
new WordJumbles("ECLIPSE");
}
}