下面列出了怎么用java.awt.dnd.DnDConstants的API类实例代码及写法,或者点击链接到github查看源代码。
ImageDragSource() {
formats = retrieveFormatsToTest();
passedArray = new boolean[formats.length];
final DragSourceListener dsl = new DragSourceAdapter() {
public void dragDropEnd(DragSourceDropEvent e) {
System.err.println("Drop was successful=" + e.getDropSuccess());
notifyTransferSuccess(e.getDropSuccess());
if (++fi < formats.length) {
leaveFormat(formats[fi]);
}
}
};
new DragSource().createDefaultDragGestureRecognizer(frame,
DnDConstants.ACTION_COPY,
dge -> dge.startDrag(null, new ImageSelection(image), dsl));
leaveFormat(formats[fi]);
}
/**
* Invoked when a mouse button is pressed on a component.
*/
public void mouseDragged(MouseEvent e) {
if (!events.isEmpty()) { // gesture pending
int dop = mapDragOperationFromModifiers(e);
if (dop == DnDConstants.ACTION_NONE) {
return;
}
MouseEvent trigger = (MouseEvent)events.get(0);
Point origin = trigger.getPoint();
Point current = e.getPoint();
int dx = Math.abs(origin.x - current.x);
int dy = Math.abs(origin.y - current.y);
if (dx > motionThreshold || dy > motionThreshold) {
fireDragGestureRecognized(dop, ((MouseEvent)getTriggerEvent()).getPoint());
} else
appendEvent(e);
}
}
/**
* Invoked when a mouse button is pressed on a component.
*/
@Override
public void mouseDragged(MouseEvent e) {
if (!events.isEmpty()) { // gesture pending
int dop = mapDragOperationFromModifiers(e);
if (dop == DnDConstants.ACTION_NONE) {
return;
}
MouseEvent trigger = (MouseEvent)events.get(0);
Point origin = trigger.getPoint();
Point current = e.getPoint();
int dx = Math.abs(origin.x - current.x);
int dy = Math.abs(origin.y - current.y);
if (dx > motionThreshold || dy > motionThreshold) {
fireDragGestureRecognized(dop, ((MouseEvent)getTriggerEvent()).getPoint());
} else
appendEvent(e);
}
}
ImageDragSource() {
formats = retrieveFormatsToTest();
passedArray = new boolean[formats.length];
final DragSourceListener dsl = new DragSourceAdapter() {
public void dragDropEnd(DragSourceDropEvent e) {
System.err.println("Drop was successful=" + e.getDropSuccess());
notifyTransferSuccess(e.getDropSuccess());
if (++fi < formats.length) {
leaveFormat(formats[fi]);
}
}
};
new DragSource().createDefaultDragGestureRecognizer(frame,
DnDConstants.ACTION_COPY,
dge -> dge.startDrag(null, new ImageSelection(image), dsl));
leaveFormat(formats[fi]);
}
private static void initAndShowUI() {
frame = new JFrame("Test frame");
frame.setSize(SIZE, SIZE);
frame.setLocationRelativeTo(null);
final JTextArea jta = new JTextArea();
jta.setBackground(Color.RED);
frame.add(jta);
jta.setText("1234567890");
jta.setFont(jta.getFont().deriveFont(150f));
jta.setDragEnabled(true);
jta.selectAll();
jta.setDropTarget(new DropTarget(jta, DnDConstants.ACTION_COPY,
new TestdropTargetListener()));
jta.addMouseListener(new TestMouseAdapter());
frame.setVisible(true);
}
private static void initAndShowUI() {
frame = new JFrame("Test frame");
frame.setSize(SIZE, SIZE);
frame.setLocationRelativeTo(null);
final JTextArea jta = new JTextArea();
jta.setBackground(Color.RED);
frame.add(jta);
jta.setText("1234567890");
jta.setFont(jta.getFont().deriveFont(150f));
jta.setDragEnabled(true);
jta.selectAll();
jta.setDropTarget(new DropTarget(jta, DnDConstants.ACTION_COPY,
new TestdropTargetListener()));
jta.addMouseListener(new TestMouseAdapter());
frame.setVisible(true);
}
/**
* mapOperation
*/
private int mapOperation(int operation) {
int[] operations = {
DnDConstants.ACTION_MOVE,
DnDConstants.ACTION_COPY,
DnDConstants.ACTION_LINK,
};
int ret = DnDConstants.ACTION_NONE;
for (int i = 0; i < operations.length; i++) {
if ((operation & operations[i]) == operations[i]) {
ret = operations[i];
break;
}
}
return ret;
}
@Test
public void testDragCopyFile2Folder() throws Exception {
DomainFolder f = rootFolder.createFolder("myFolder");
createNotepadFile(f);
GTreeNode winNode = getChild(rootNode, "tms");
GTreeNode myNode = getChild(rootNode, "myFolder");
assertNotNull(myNode);
setSelectionPaths(new TreePath[] { myNode.getTreePath() });
doDrag(myNode, DnDConstants.ACTION_COPY, winNode);
waitForTree();
// myFolder should have 2 files
expandTreePath(myNode.getTreePath());
assertEquals(2, myNode.getChildCount());
assertNotNull(getChild(rootNode, "tms"));
}
private boolean processXdndStatus(XClientMessageEvent xclient) {
int action = DnDConstants.ACTION_NONE;
/* Ignore XDnD messages from all other windows. */
if (xclient.get_data(0) != getTargetWindow()) {
return true;
}
if ((xclient.get_data(1) & XDnDConstants.XDND_ACCEPT_DROP_FLAG) != 0) {
/* This feature is new in XDnD version 2, but we can use it as XDnD
compliance only requires supporting version 3 and up. */
action = XDnDConstants.getJavaActionForXDnDAction(xclient.get_data(4));
}
getProtocolListener().handleDragReply(action);
return true;
}
/**
* Invoked when a mouse button is pressed on a component.
*/
@Override
public void mouseDragged(MouseEvent e) {
if (!events.isEmpty()) { // gesture pending
int dop = mapDragOperationFromModifiers(e);
if (dop == DnDConstants.ACTION_NONE) {
return;
}
MouseEvent trigger = (MouseEvent)events.get(0);
Point origin = trigger.getPoint();
Point current = e.getPoint();
int dx = Math.abs(origin.x - current.x);
int dy = Math.abs(origin.y - current.y);
if (dx > motionThreshold || dy > motionThreshold) {
fireDragGestureRecognized(dop, ((MouseEvent)getTriggerEvent()).getPoint());
} else
appendEvent(e);
}
}
private void doUpdateTargetWindow(long subwindow, long time) {
long clientWindow = 0;
long proxyWindow = 0;
XDragSourceProtocol protocol = null;
boolean isReceiver = false;
if (subwindow != 0) {
clientWindow = findClientWindow(subwindow);
}
if (clientWindow != 0) {
Iterator dragProtocols = XDragAndDropProtocols.getDragSourceProtocols();
while (dragProtocols.hasNext()) {
XDragSourceProtocol dragProtocol = (XDragSourceProtocol)dragProtocols.next();
if (dragProtocol.attachTargetWindow(clientWindow, time)) {
protocol = dragProtocol;
break;
}
}
}
/* Update the global state. */
dragProtocol = protocol;
targetAction = DnDConstants.ACTION_NONE;
targetRootSubwindow = subwindow;
}
ImageDragSource() {
formats = retrieveFormatsToTest();
passedArray = new boolean[formats.length];
final DragSourceListener dsl = new DragSourceAdapter() {
public void dragDropEnd(DragSourceDropEvent e) {
System.err.println("Drop was successful=" + e.getDropSuccess());
notifyTransferSuccess(e.getDropSuccess());
if (++fi < formats.length) {
leaveFormat(formats[fi]);
}
}
};
new DragSource().createDefaultDragGestureRecognizer(frame,
DnDConstants.ACTION_COPY,
dge -> dge.startDrag(null, new ImageSelection(image), dsl));
leaveFormat(formats[fi]);
}
/**
* mapOperation
*/
private int mapOperation(int operation) {
int[] operations = {
DnDConstants.ACTION_MOVE,
DnDConstants.ACTION_COPY,
DnDConstants.ACTION_LINK,
};
int ret = DnDConstants.ACTION_NONE;
for (int i = 0; i < operations.length; i++) {
if ((operation & operations[i]) == operations[i]) {
ret = operations[i];
break;
}
}
return ret;
}
/**
* determine the drop action from the event
*/
protected int mapDragOperationFromModifiers(MouseEvent e) {
int mods = e.getModifiersEx();
int btns = mods & ButtonMask;
// Prohibit multi-button drags.
if (!(btns == InputEvent.BUTTON1_DOWN_MASK ||
btns == InputEvent.BUTTON2_DOWN_MASK ||
btns == InputEvent.BUTTON3_DOWN_MASK)) {
return DnDConstants.ACTION_NONE;
}
return
SunDragSourceContextPeer.convertModifiersToDropAction(mods,
getSourceActions());
}
@Test
public void testDropSiteOK2() throws Exception {
// verify that a SymbolCategory is not a valid drop site
GTreeNode nsNode = rootNode.getChild(5);
util.createObject(nsNode, "MyNamespace", createNamespaceAction);
GTreeNode fNode = rootNode.getChild(2);
util.expandNode(fNode);
GTreeNode gNode = fNode.getChild(1);
GTreeNode sNode = fNode.getChild(2);
util.selectNodes(new GTreeNode[] { gNode, sNode });
GTreeNode extNode = rootNode.getChild(0);
DataFlavor flavor = ((SymbolTreeNode) gNode).getNodeDataFlavor();
GTreeDragNDropHandler dnd = util.getTree().getDragNDropHandler();
assertTrue(
!dnd.isDropSiteOk(extNode, new DataFlavor[] { flavor }, DnDConstants.ACTION_MOVE));
assertTrue(
!dnd.isDropSiteOk(extNode, new DataFlavor[] { flavor }, DnDConstants.ACTION_COPY));
}
/**
* mapOperation
*/
private int mapOperation(int operation) {
int[] operations = {
DnDConstants.ACTION_MOVE,
DnDConstants.ACTION_COPY,
DnDConstants.ACTION_LINK,
};
int ret = DnDConstants.ACTION_NONE;
for (int i = 0; i < operations.length; i++) {
if ((operation & operations[i]) == operations[i]) {
ret = operations[i];
break;
}
}
return ret;
}
/**
* mapOperation
*/
private int mapOperation(int operation) {
int[] operations = {
DnDConstants.ACTION_MOVE,
DnDConstants.ACTION_COPY,
DnDConstants.ACTION_LINK,
};
int ret = DnDConstants.ACTION_NONE;
for (int i = 0; i < operations.length; i++) {
if ((operation & operations[i]) == operations[i]) {
ret = operations[i];
break;
}
}
return ret;
}
/**
* signal drop complete
*/
public synchronized void dropComplete(boolean success) {
if (dropStatus == STATUS_NONE) {
throw new InvalidDnDOperationException("No Drop pending");
}
if (currentDTC != null) {
AWTAccessor.getDropTargetContextAccessor().reset(currentDTC);
}
currentDT = null;
currentDTC = null;
currentT = null;
currentA = DnDConstants.ACTION_NONE;
synchronized(_globalLock) {
currentJVMLocalSourceTransferable = null;
}
dropStatus = STATUS_NONE;
dropComplete = true;
try {
doDropDone(success, currentDA, local != null);
} finally {
currentDA = DnDConstants.ACTION_NONE;
// The native context is invalid after the drop is done.
// Clear the reference to prohibit access.
nativeDragContext = 0;
}
}
/**
* actual processing on EventQueue Thread
*/
protected void processEnterMessage(SunDropTargetEvent event) {
Component c = (Component)event.getSource();
DropTarget dt = c.getDropTarget();
Point hots = event.getPoint();
local = getJVMLocalSourceTransferable();
if (currentDTC != null) { // some wreckage from last time
currentDTC.removeNotify();
currentDTC = null;
}
if (c.isShowing() && dt != null && dt.isActive()) {
currentDT = dt;
currentDTC = currentDT.getDropTargetContext();
currentDTC.addNotify(this);
currentA = dt.getDefaultActions();
try {
((DropTargetListener)dt).dragEnter(new DropTargetDragEvent(currentDTC,
hots,
currentDA,
currentSA));
} catch (Exception e) {
e.printStackTrace();
currentDA = DnDConstants.ACTION_NONE;
}
} else {
currentDT = null;
currentDTC = null;
currentDA = DnDConstants.ACTION_NONE;
currentSA = DnDConstants.ACTION_NONE;
currentA = DnDConstants.ACTION_NONE;
}
}
SourceFileListFrame() {
super("Source File List Frame");
extractFilesFromTheWorkingDirectory();
initList();
initGUI();
new DragSource().createDefaultDragGestureRecognizer(list,
DnDConstants.ACTION_COPY,this);
}
/**
* actual processing on EventQueue Thread
*/
protected void processEnterMessage(SunDropTargetEvent event) {
Component c = (Component)event.getSource();
DropTarget dt = c.getDropTarget();
Point hots = event.getPoint();
local = getJVMLocalSourceTransferable();
if (currentDTC != null) { // some wreckage from last time
currentDTC.removeNotify();
currentDTC = null;
}
if (c.isShowing() && dt != null && dt.isActive()) {
currentDT = dt;
currentDTC = currentDT.getDropTargetContext();
currentDTC.addNotify(this);
currentA = dt.getDefaultActions();
try {
((DropTargetListener)dt).dragEnter(new DropTargetDragEvent(currentDTC,
hots,
currentDA,
currentSA));
} catch (Exception e) {
e.printStackTrace();
currentDA = DnDConstants.ACTION_NONE;
}
} else {
currentDT = null;
currentDTC = null;
currentDA = DnDConstants.ACTION_NONE;
currentSA = DnDConstants.ACTION_NONE;
currentA = DnDConstants.ACTION_NONE;
}
}
/**
* upcall to handle exit messages
*/
private void handleExitMessage(final Component component,
final long nativeCtxt) {
/*
* Even though the return value is irrelevant for this event, it is
* dispatched synchronously to fix 4393148 properly.
*/
postDropTargetEvent(component, 0, 0, DnDConstants.ACTION_NONE,
DnDConstants.ACTION_NONE, null, nativeCtxt,
SunDropTargetEvent.MOUSE_EXITED,
SunDropTargetContextPeer.DISPATCH_SYNC);
}
/**
* Invoked when a mouse button has been pressed on a component.
*/
public void mousePressed(MouseEvent e) {
events.clear();
if (mapDragOperationFromModifiers(e) != DnDConstants.ACTION_NONE) {
try {
motionThreshold = DragSource.getDragThreshold();
} catch (Exception exc) {
motionThreshold = 5;
}
appendEvent(e);
}
}
/**
*
*/
private void dropHandle() {
// Handle drag & drop files into jPanel
jPanel_Device.setDropTarget(new DropTarget() {
@Override
public synchronized void drop(DropTargetDropEvent dtde) {
// disable UI
try {
// set accepted drop action
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
// Just going to grab the expected DataFlavor to make sure
// we know what is being dropped
// Grab expected flavor
DataFlavor dragAndDropPanelFlavor = DataFlavor.javaFileListFlavor;
// What does the Transferable support
if (dtde.getTransferable().isDataFlavorSupported(dragAndDropPanelFlavor)) {
Object transferableArrayListObj = dtde.getTransferable().getTransferData(dragAndDropPanelFlavor);
if (transferableArrayListObj != null) {
if (transferableArrayListObj instanceof ArrayList) {
// copyHandle
List<MyFile> src = new ArrayList<>();
((ArrayList) transferableArrayListObj).forEach(file -> {
String srcFile = ((File) file).getAbsolutePath();
src.add(new MyFile(srcFile, 0, 0, 0));
});
// copy from local
fileBrowserLocal.onCopy(src);
// paste to device
fileBrowserDevice.onPaste();
}
}
}
} catch (UnsupportedFlavorException | IOException ex) {
Log.log(Level.SEVERE, "DropItHandle", ex);
}
// handle drop inside current panel
//super.drop(dtde);*/
}
});
}
static int getJavaActionForXDnDAction(long xdndAction) {
if (xdndAction == XA_XdndActionCopy.getAtom()) {
return DnDConstants.ACTION_COPY;
} else if (xdndAction == XA_XdndActionMove.getAtom()) {
return DnDConstants.ACTION_MOVE;
} else if (xdndAction == XA_XdndActionLink.getAtom()) {
return DnDConstants.ACTION_LINK;
} else {
return DnDConstants.ACTION_NONE;
}
}
SourceFileListFrame() {
super("Source File List Frame");
extractFilesFromTheWorkingDirectory();
initList();
initGUI();
new DragSource().createDefaultDragGestureRecognizer(list,
DnDConstants.ACTION_COPY,this);
}
public static int convertModifiersToDropAction(final int modifiers,
final int supportedActions) {
int dropAction = DnDConstants.ACTION_NONE;
/*
* Fix for 4285634.
* Calculate the drop action to match Motif DnD behavior.
* If the user selects an operation (by pressing a modifier key),
* return the selected operation or ACTION_NONE if the selected
* operation is not supported by the drag source.
* If the user doesn't select an operation search the set of operations
* supported by the drag source for ACTION_MOVE, then for
* ACTION_COPY, then for ACTION_LINK and return the first operation
* found.
*/
switch (modifiers & (InputEvent.SHIFT_DOWN_MASK |
InputEvent.CTRL_DOWN_MASK)) {
case InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK:
dropAction = DnDConstants.ACTION_LINK; break;
case InputEvent.CTRL_DOWN_MASK:
dropAction = DnDConstants.ACTION_COPY; break;
case InputEvent.SHIFT_DOWN_MASK:
dropAction = DnDConstants.ACTION_MOVE; break;
default:
if ((supportedActions & DnDConstants.ACTION_MOVE) != 0) {
dropAction = DnDConstants.ACTION_MOVE;
} else if ((supportedActions & DnDConstants.ACTION_COPY) != 0) {
dropAction = DnDConstants.ACTION_COPY;
} else if ((supportedActions & DnDConstants.ACTION_LINK) != 0) {
dropAction = DnDConstants.ACTION_LINK;
}
}
return dropAction & supportedActions;
}
public SourcePanel() {
setPreferredSize(new Dimension(200, 200));
DragSource defaultDragSource =
DragSource.getDefaultDragSource();
defaultDragSource.createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY_OR_MOVE, dragGestureListener);
setBackground(Color.RED);
}
/**
* Invoked when a mouse button has been pressed on a component.
*/
@Override
public void mousePressed(MouseEvent e) {
events.clear();
if (mapDragOperationFromModifiers(e) != DnDConstants.ACTION_NONE) {
try {
motionThreshold = DragSource.getDragThreshold();
} catch (Exception exc) {
motionThreshold = 5;
}
appendEvent(e);
}
}
/**
* Invoked when the mouse exits a component.
*/
@Override
public void mouseExited(MouseEvent e) {
if (!events.isEmpty()) { // gesture pending
int dragAction = mapDragOperationFromModifiers(e);
if (dragAction == DnDConstants.ACTION_NONE) {
events.clear();
}
}
}