下面列出了怎么用java.awt.dnd.DragSource的API类实例代码及写法,或者点击链接到github查看源代码。
public DraggableButton(final Action action) {
super(action);
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent event) {
getTransferHandler().exportAsDrag(DraggableButton.this, event, TransferHandler.COPY);
}
});
t = new TransferHandler("graph") {
@Override
public Transferable createTransferable(final JComponent c) {
return new StringSelection("graphSelection");
}
};
setTransferHandler(t);
source = new DragSource();
source.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, this);
}
@Override
public void dragGestureRecognized(DragGestureEvent event) {
// only allow dragging with left mouse button
if (event.getTriggerEvent().getModifiers() != InputEvent.BUTTON1_MASK) {
return;
}
// change cursor to drag move
Cursor cursor = null;
if (event.getDragAction() == DnDConstants.ACTION_COPY) {
cursor = DragSource.DefaultCopyDrop;
}
// set the repository entry as the Transferable
TransferableRepositoryEntry transferable = new TransferableRepositoryEntry(location);
if (usageLogger != null) {
transferable.setUsageStatsLogger(usageLogger);
} else if (usageObject != null) {
transferable.setUsageObject(usageObject);
}
event.startDrag(cursor, transferable);
}
@Override
public void mouseDragged(MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e) && dragStartPoint != null)
{
Point point = e.getPoint();
if (draggingComponent != null)
{
drag(point);
}
else if (point.distance(dragStartPoint) > DragSource.getDragThreshold())
{
startDragging(point);
}
}
}
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]);
}
public void start() {
Frame f = new Frame("Use keyboard for DnD change");
Panel mainPanel;
Component dragSource, dropTarget;
f.setBounds(0, 400, 200, 200);
f.setLayout(new BorderLayout());
mainPanel = new Panel();
mainPanel.setLayout(new BorderLayout());
mainPanel.setBackground(Color.blue);
dropTarget = new DnDTarget(Color.red, Color.yellow);
dragSource = new DnDSource("Drag ME! (" + (DragSource.isDragImageSupported()?"with ":"without") + " image)" );
mainPanel.add(dragSource, "North");
mainPanel.add(dropTarget, "Center");
f.add(mainPanel, BorderLayout.CENTER);
f.setVisible(true);
}
public void start() {
Frame f = new Frame("Use keyboard for DnD change");
Panel mainPanel;
Component dragSource, dropTarget;
f.setBounds(0, 400, 200, 200);
f.setLayout(new BorderLayout());
mainPanel = new Panel();
mainPanel.setLayout(new BorderLayout());
mainPanel.setBackground(Color.blue);
dropTarget = new DnDTarget(Color.red, Color.yellow);
dragSource = new DnDSource("Drag ME! (" + (DragSource.isDragImageSupported()?"with ":"without") + " image)" );
mainPanel.add(dragSource, "North");
mainPanel.add(dropTarget, "Center");
f.add(mainPanel, BorderLayout.CENTER);
f.setVisible(true);
}
public void start() {
Frame f = new Frame("Use keyboard for DnD change");
Panel mainPanel;
Component dragSource, dropTarget;
f.setBounds(0, 400, 200, 200);
f.setLayout(new BorderLayout());
mainPanel = new Panel();
mainPanel.setLayout(new BorderLayout());
mainPanel.setBackground(Color.blue);
dropTarget = new DnDTarget(Color.red, Color.yellow);
dragSource = new DnDSource("Drag ME! (" + (DragSource.isDragImageSupported()?"with ":"without") + " image)" );
mainPanel.add(dragSource, "North");
mainPanel.add(dropTarget, "Center");
f.add(mainPanel, BorderLayout.CENTER);
f.setVisible(true);
}
private boolean triggerDrag(JFrame f, Point p, DragGestureEvent dge,
JComponent c) {
Rectangle r = new Rectangle(0, 0, c.getWidth(), c.getHeight());
r = SwingUtilities.convertRectangle(c, r, f);
if (r.contains(p)) {
draggingFromToolbar = true;
draggingDefaults = false;
draggingComponent = c.getName();
MockComponent mc = new MockComponent(c);
Transferable transferable = new MockComponentTransferable(mc);
BufferedImage bi = mc.getBufferedImage();
dge.startDrag(DragSource.DefaultMoveDrop, bi, new Point(r.x
- p.x, r.y - p.y), transferable, dragSourceListener);
return true;
}
return false;
}
@Override
public <T extends DragGestureRecognizer> T
createDragGestureRecognizer(Class<T> abstractRecognizerClass,
DragSource ds, Component c, int srcActions,
DragGestureListener dgl)
{
final LightweightFrame f = SunToolkit.getLightweightFrame(c);
if (f != null) {
return f.createDragGestureRecognizer(abstractRecognizerClass, ds, c, srcActions, dgl);
}
if (MouseDragGestureRecognizer.class.equals(abstractRecognizerClass))
return (T)new WMouseDragGestureRecognizer(ds, c, srcActions, dgl);
else
return null;
}
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]);
}
@Override
public <T extends DragGestureRecognizer> T
createDragGestureRecognizer(Class<T> abstractRecognizerClass,
DragSource ds, Component c, int srcActions,
DragGestureListener dgl)
{
final LightweightFrame f = SunToolkit.getLightweightFrame(c);
if (f != null) {
return f.createDragGestureRecognizer(abstractRecognizerClass, ds, c, srcActions, dgl);
}
if (MouseDragGestureRecognizer.class.equals(abstractRecognizerClass))
return (T)new WMouseDragGestureRecognizer(ds, c, srcActions, dgl);
else
return null;
}
public SourcePanel() {
setPreferredSize(new Dimension(200, 200));
DragSource defaultDragSource =
DragSource.getDefaultDragSource();
defaultDragSource.createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY_OR_MOVE, dragGestureListener);
setBackground(Color.RED);
}
/**
* Create a drag gesture recognizer for the lightweight frame.
*/
default public <T extends DragGestureRecognizer> T createDragGestureRecognizer(
Class<T> abstractRecognizerClass,
DragSource ds, Component c, int srcActions,
DragGestureListener dgl)
{
return null;
}
SourceFileListFrame() {
super("Source File List Frame");
extractFilesFromTheWorkingDirectory();
initList();
initGUI();
new DragSource().createDefaultDragGestureRecognizer(list,
DnDConstants.ACTION_COPY,this);
}
/**
* Returns whether or not the event is potentially part of a drag sequence.
*/
private boolean mousePressedImpl(MouseEvent me) {
component = (JComponent)me.getSource();
if (mapDragOperationFromModifiers(me, component.getTransferHandler())
!= TransferHandler.NONE) {
motionThreshold = DragSource.getDragThreshold();
dndArmedEvent = me;
return true;
}
clearState();
return false;
}
/**
* 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);
}
}
/**
*
* @param treeModel
* @param cPanel
*/
public OutputTree(OutputTreeModel treeModel) {
this.setModel(treeModel);
DragSource dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY, this);
}
/**
* 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);
}
}
/**
* Returns whether or not the event is potentially part of a drag sequence.
*/
private boolean mousePressedImpl(MouseEvent me) {
component = (JComponent)me.getSource();
if (mapDragOperationFromModifiers(me, component.getTransferHandler())
!= TransferHandler.NONE) {
motionThreshold = DragSource.getDragThreshold();
dndArmedEvent = me;
return true;
}
clearState();
return false;
}
/**
* 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);
}
}
@Override
public <T extends DragGestureRecognizer> T
createDragGestureRecognizer(Class<T> abstractRecognizerClass,
DragSource ds, Component c,
int srcActions, DragGestureListener dgl)
{
return null;
}
public static void main(String[] args) throws Exception {
Frame sourceFrame = createFrame("Source Frame", 0, 0);
Frame targetFrame = createFrame("Target Frame", 250, 250);
DragSource defaultDragSource
= DragSource.getDefaultDragSource();
defaultDragSource.createDefaultDragGestureRecognizer(sourceFrame,
DnDConstants.ACTION_COPY_OR_MOVE,
new TestDragGestureListener());
new DropTarget(targetFrame, DnDConstants.ACTION_COPY_OR_MOVE,
new TestDropTargetListener(targetFrame));
Robot robot = new Robot();
robot.setAutoDelay(50);
sourceFrame.toFront();
robot.waitForIdle();
Point point = getCenterPoint(sourceFrame);
robot.mouseMove(point.x, point.y);
robot.waitForIdle();
mouseDragAndDrop(robot, point, getCenterPoint(targetFrame));
long time = System.currentTimeMillis() + 1000;
while (!passed) {
if (time < System.currentTimeMillis()) {
sourceFrame.dispose();
targetFrame.dispose();
throw new RuntimeException("Mouse clicked event is lost!");
}
Thread.sleep(10);
}
sourceFrame.dispose();
targetFrame.dispose();
}
public void dragGestureRecognized( final DragGestureEvent anEvent ) {
final ElementMetaData elementMetaData = ElementTypeRegistry.getInstance().getElementType( elementName );
final ElementMetaDataTransferable transferable = new ElementMetaDataTransferable( elementMetaData );
anEvent.startDrag( DragSource.DefaultCopyNoDrop, EMPTY_DRAG_IMAGE, new Point(), transferable, null );
final ButtonModel model = getModel();
model.setArmed( false );
model.setPressed( false );
}
/**
* Create a drag gesture recognizer for the lightweight frame.
*/
default public <T extends DragGestureRecognizer> T createDragGestureRecognizer(
Class<T> abstractRecognizerClass,
DragSource ds, Component c, int srcActions,
DragGestureListener dgl)
{
return null;
}
/**
* 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);
}
}
public SourcePanel () {
setPreferredSize(new Dimension(200, 200));
DragSource defaultDragSource =
DragSource.getDefaultDragSource();
defaultDragSource.createDefaultDragGestureRecognizer(this,
DnDConstants.ACTION_COPY_OR_MOVE, dragGestureListener);
setBackground(Color.RED);
}
@Override
public <T extends DragGestureRecognizer> T
createDragGestureRecognizer(Class<T> abstractRecognizerClass,
DragSource ds, Component c,
int srcActions, DragGestureListener dgl)
{
return null;
}
SourceFileListFrame() {
super("Source File List Frame");
extractFilesFromTheWorkingDirectory();
initList();
initGUI();
new DragSource().createDefaultDragGestureRecognizer(list,
DnDConstants.ACTION_COPY,this);
}
SourceFileListFrame() {
super("Source File List Frame");
extractFilesFromTheWorkingDirectory();
initList();
initGUI();
new DragSource().createDefaultDragGestureRecognizer(list,
DnDConstants.ACTION_COPY,this);
}
/**
* 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);
}
}