Класс DragSourceContext

Все реализованные интерфейсы:
DragSourceListener, DragSourceMotionListener, Serializable, EventListener
public class DragSourceContext
extends Object
implements DragSourceListener, DragSourceMotionListener, Serializable

Класс DragSourceContext отвечает за управление инициаторской стороной протокола «Перетаскивание». В частности, он отвечает за управление уведомлениями о событиях перетаскивания для DragSourceListeners и DragSourceMotionListeners, а также за предоставление Transferable, представляющего исходные данные для операции перетаскивания.

Обратите внимание, что сам DragSourceContext реализует интерфейсы DragSourceListener и DragSourceMotionListener. Это позволяет платформенному компоненту (экземпляру DragSourceContextPeer), созданному с помощью DragSource, уведомлять DragSourceContext об изменениях состояния в текущей операции. Это позволяет объекту DragSourceContext размещаться между платформой и слушателями, предоставленными инициатором операции перетаскивания.

По умолчанию DragSourceContext устанавливает курсор соответствующим образом для текущего состояния операции перетаскивания. Например, если пользователь выбрал действие перемещения, и указатель находится над целью, которая принимает действие перемещения, отображается курсор перемещения по умолчанию. Когда указатель находится над областью, которая не принимает передачу, отображается курсор «нет перетаскивания» по умолчанию.

Этот механизм обработки по умолчанию отключается, когда пользовательский курсор устанавливается с помощью метода setCursor(java.awt.Cursor). Когда обработка по умолчанию отключена, разработчик отвечает за обновление курсора, прослушивая события DragSource и вызывая метод setCursor(). В качестве альтернативы, вы можете обеспечить пользовательское поведение курсора, предоставив пользовательские реализации классов DragSource и DragSourceContext.

С момента:
1.2
См. также:
DragSourceListener, DragSourceMotionListener, DnDConstants, Serialized Form

Краткое описание полей

Модификатор и тип Поле Описание
protected static int CHANGED

An int used by updateCurrentCursor() indicating that the user operation has changed.

protected static int DEFAULT

An int used by updateCurrentCursor() indicating that the Cursor should change to the default (no drop) Cursor.

protected static int ENTER

An int used by updateCurrentCursor() indicating that the Cursor has entered a DropTarget.

protected static int OVER

An int used by updateCurrentCursor() indicating that the Cursor is over a DropTarget.

Краткое описание конструкторов

Конструктор Описание
DragSourceContext​(DragGestureEvent trigger, Cursor dragCursor, Image dragImage, Point offset, Transferable t, DragSourceListener dsl)

Called from DragSource, this constructor creates a new DragSourceContext given the DragSourceContextPeer for this Drag, the DragGestureEvent that triggered the Drag, the initial Cursor to use for the Drag, an (optional) Image to display while the Drag is taking place, the offset of the Image origin from the hotspot at the instant of the triggering event, the Transferable subject data, and the DragSourceListener to use during the Drag and Drop operation.

Краткое описание методов

Модификатор и тип Метод Описание
void addDragSourceListener​(DragSourceListener dsl)

Add a DragSourceListener to this DragSourceContext if one has not already been added.

void dragDropEnd​(DragSourceDropEvent dsde)

Calls dragDropEnd on the DragSourceListeners registered with this DragSourceContext and with the associated DragSource, and passes them the specified DragSourceDropEvent.

void dragEnter​(DragSourceDragEvent dsde)

Calls dragEnter on the DragSourceListeners registered with this DragSourceContext and with the associated DragSource, and passes them the specified DragSourceDragEvent.

void dragExit​(DragSourceEvent dse)

Calls dragExit on the DragSourceListeners registered with this DragSourceContext and with the associated DragSource, and passes them the specified DragSourceEvent.

void dragMouseMoved​(DragSourceDragEvent dsde)

Calls dragMouseMoved on the DragSourceMotionListeners registered with the DragSource associated with this DragSourceContext, and them passes the specified DragSourceDragEvent.

void dragOver​(DragSourceDragEvent dsde)

Calls dragOver on the DragSourceListeners registered with this DragSourceContext and with the associated DragSource, and passes them the specified DragSourceDragEvent.

void dropActionChanged​(DragSourceDragEvent dsde)

Calls dropActionChanged on the DragSourceListeners registered with this DragSourceContext and with the associated DragSource, and passes them the specified DragSourceDragEvent.

Component getComponent()

Returns the Component associated with this DragSourceContext.

Cursor getCursor()

Returns the current custom drag Cursor.

DragSource getDragSource()

Returns the DragSource that instantiated this DragSourceContext.

int getSourceActions()

Returns a bitwise mask of DnDConstants that represent the set of drop actions supported by the drag source for the drag operation associated with this DragSourceContext.

Transferable getTransferable()

Returns the Transferable associated with this DragSourceContext.

DragGestureEvent getTrigger()

Returns the DragGestureEvent that initially triggered the drag.

void removeDragSourceListener​(DragSourceListener dsl)

Removes the specified DragSourceListener from this DragSourceContext.

void setCursor​(Cursor c)

Sets the custom cursor for this drag operation to the specified Cursor.

void transferablesFlavorsChanged()

Notifies the peer that the Transferable's DataFlavors have changed.

protected void updateCurrentCursor​(int sourceAct, int targetAct, int status)

If the default drag cursor behavior is active, this method sets the default drag cursor for the specified actions supported by the drag source, the drop target action, and status, otherwise this method does nothing.

Методы, объявленные в классе java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Поля

DEFAULT

protected static final int DEFAULT

Значение, используемое методом updateCurrentCursor(), указывающее, что курсор должен измениться на стандартный (без отпускания) Cursor.

См. также:
Значения константных полей

ENTER

protected static final int ENTER

Значение, используемое методом updateCurrentCursor(), указывающее, что курсор вошёл в DropTarget.

См. также:
Значения константных полей

OVER

protected static final int OVER

Значение, используемое методом updateCurrentCursor(), указывающее, что курсор находится над DropTarget.

См. также:
Значения константных полей

CHANGED

protected static final int CHANGED

Значение, используемое методом updateCurrentCursor(), указывающее, что пользовательское действие изменилось.

См. также:
Значения константных полей

Конструкторы

DragSourceContext

public DragSourceContext(DragGestureEvent trigger,
                         Cursor dragCursor,
                         Image dragImage,
                         Point offset,
                         Transferable t,
                         DragSourceListener dsl)

Вызывается из DragSource, этот конструктор создаёт новый DragSourceContext с учётом DragSourceContextPeer для данного перетаскивания, DragGestureEvent , вызвавшего перетаскивание, начального Cursor для перетаскивания, (необязательного) Image для отображения во время перетаскивания, смещения начала Image от горячей точки в момент триггерного события, Transferable данных, и DragSourceListener для использования во время операции перетаскивания и опускания.
Если DragSourceContextPeer null NullPointerException выбрасывается.
Если DragGestureEvent null NullPointerException выбрасывается.
Если Cursor null исключение не выбрасывается, и активируется стандартное поведение курсора для данного перетаскивания.
Если Image null исключение не выбрасывается.
Если Image не null и смещение null NullPointerException выбрасывается.
Если Transferable null NullPointerException выбрасывается.
Если DragSourceListener null исключение не выбрасывается.

Параметры:
trigger - событие срабатывания
dragCursor - начальный Cursor для этой операции перетаскивания или null для стандартной обработки курсора; см. документацию уровня класса для получения более подробной информации о механизме обработки курсора во время перетаскивания и опускания
dragImage - Image для перетаскивания (или null)
offset - смещение начала изображения от горячей точки в момент срабатывания события
t - Transferable
dsl - DragSourceListener
Исключения:
IllegalArgumentException - если Component , связанное с событием срабатывания, null.
IllegalArgumentException - если DragSource для события срабатывания null.
IllegalArgumentException - если действие перетаскивания для события срабатывания DnDConstants.ACTION_NONE.
IllegalArgumentException - если действия источника для DragGestureRecognizer , связанного с событием срабатывания, равны DnDConstants.ACTION_NONE.
NullPointerException - если dscp, trigger или t равны null, или если dragImage не равно null, а offset равно null

Методы

getDragSource

public DragSource getDragSource()

Возвращает DragSource , который инициировал этот DragSourceContext.

Возвращает:
DragSource , который инициировал этот DragSourceContext

getComponent

public Component getComponent()

Возвращает Component , связанный с этим DragSourceContext.

Возвращает:
Component , который начал перетаскивание

getTrigger

public DragGestureEvent getTrigger()

Возвращает DragGestureEvent , который первоначально инициировал перетаскивание.

Возвращает:
событие, которое инициировало перетаскивание

getSourceActions

public int getSourceActions()

Возвращает битовую маску DnDConstants , представляющую набор действий по выбросу, поддерживаемых источником перетаскивания для операции перетаскивания, связанной с этим DragSourceContext.

Возвращает:
действия по выбросу, поддерживаемые источником перетаскивания

setCursor

public void setCursor(Cursor c)

Устанавливает пользовательский курсор для этой операции перетаскивания на указанный Cursor. Если указанный Cursor равен null, поведение курсора по умолчанию для этой операции перетаскивания активируется, в противном случае оно деактивируется.

Параметры:
c - начальный Cursor для этой операции перетаскивания или null для обработки курсора по умолчанию; см. документацию уровня класса для получения дополнительных сведений об обработке курсора во время перетаскивания и выброса

getCursor

public Cursor getCursor()

Возвращает текущий пользовательский курсор перетаскивания Cursor.

Возвращает:
текущий пользовательский курсор перетаскивания Cursor, если он был установлен, в противном случае возвращает null.
См. также:
setCursor(java.awt.Cursor)

addDragSourceListener

public void addDragSourceListener(DragSourceListener dsl)
                           throws TooManyListenersException

Добавляет DragSourceListener к этому DragSourceContext , если он еще не был добавлен. Если DragSourceListener уже существует, этот метод генерирует TooManyListenersException.

Параметры:
dsl - добавляемый DragSourceListener . Обратите внимание, что хотя null не запрещено, его использование в качестве параметра неприемлемо.
Исключения:
TooManyListenersException - если DragSourceListener уже был добавлен

removeDragSourceListener

public void removeDragSourceListener(DragSourceListener dsl)

Удаляет указанный DragSourceListener из этого DragSourceContext.

Параметры:
dsl - удаляемый DragSourceListener ; обратите внимание, что хотя null не запрещено, его использование в качестве параметра неприемлемо

transferablesFlavorsChanged

public void transferablesFlavorsChanged()

Уведомляет peer о том, что Transferable DataFlavor изменились.

dragEnter

public void dragEnter(DragSourceDragEvent dsde)

Вызывает dragEnter на зарегистрированных с этим DragSourceContext и связанным DragSource DragSourceListener и передает им указанное DragSourceDragEvent.

Унаследовано от:
dragEnter в интерфейсе DragSourceListener
Параметры:
dsde - DragSourceDragEvent

dragOver

public void dragOver(DragSourceDragEvent dsde)

Вызывает dragOver на зарегистрированных с этим DragSourceContext и связанным DragSource DragSourceListener и передает им указанное DragSourceDragEvent.

Унаследовано от:
dragOver в интерфейсе DragSourceListener
Параметры:
dsde - DragSourceDragEvent

dragExit

public void dragExit(DragSourceEvent dse)

Вызывает dragExit на зарегистрированных с этим DragSourceContext и связанным DragSource DragSourceListener и передает им указанное DragSourceEvent.

Унаследовано от:
dragExit в интерфейсе DragSourceListener
Параметры:
dse - DragSourceEvent

dropActionChanged

public void dropActionChanged(DragSourceDragEvent dsde)

Вызывает dropActionChanged на зарегистрированных с этим DragSourceContext и связанным DragSource DragSourceListener и передает им указанное DragSourceDragEvent.

Унаследовано от:
dropActionChanged в интерфейсе DragSourceListener
Параметры:
dsde - DragSourceDragEvent

dragDropEnd

public void dragDropEnd(DragSourceDropEvent dsde)

Вызывает dragDropEnd на зарегистрированных с этим DragSourceContext и связанным DragSource DragSourceListener и передает им указанное DragSourceDropEvent.

Унаследовано от:
dragDropEnd в интерфейсе DragSourceListener
Параметры:
dsde - DragSourceDropEvent

dragMouseMoved

public void dragMouseMoved(DragSourceDragEvent dsde)

Вызывает dragMouseMoved на зарегистрированных с DragSource , связанным с этим DragSourceContext, и передает им указанное DragSourceDragEvent.

Унаследовано от:
dragMouseMoved в интерфейсе DragSourceMotionListener
Параметры:
dsde - DragSourceDragEvent
С:
1.4

getTransferable

public Transferable getTransferable()

Возвращает Transferable , связанный с этим DragSourceContext.

Возвращает:
Transferable

updateCurrentCursor

protected void updateCurrentCursor(int sourceAct,
                                   int targetAct,
                                   int status)

Если активна обработка курсора по умолчанию для перетаскивания, этот метод устанавливает курсор перетаскивания по умолчанию для указанных действий, поддерживаемых источником перетаскивания, целевым действием выброса и статусом. В противном случае этот метод ничего не делает.

Параметры:
sourceAct - действия, поддерживаемые источником перетаскивания
targetAct - действие целевого выброса
status - одно из полей DEFAULT, ENTER, OVER, CHANGED

© 1993, 2020, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/awt/dnd/DragSourceContext.html

Spec-Zone .ru
спецификации, руководства, описания, API