我有一个自定义小部件,实际上是一个图像,我希望能够将它拖到AbsolutePanel内并每次都得到它的坐标。我想使用GWT 2.4的新DND API,但我很难实现它。有人可以提出我必须采取的基本步骤吗?
答案 0 :(得分:12)
GWT 2.4引入的新DnD API目前不支持AbsolutePanel
(请参阅HasAllDragAndDropHandlers
接口的实现)。看看FocusPanel
的实现,为其他小组启用它应该不会太难。
以下是关于如何解决问题的概念的快速证明:
public void onModuleLoad() {
DragImage image = new DragImage();
image.setUrl(Resources.INSTANCE.someImage().getSafeUri());
final DropAbsolutePanel target = new DropAbsolutePanel();
target.getElement().getStyle().setBorderWidth(1.0, Unit.PX);
target.getElement().getStyle().setBorderStyle(BorderStyle.SOLID);
target.getElement().getStyle().setBorderColor("black");
target.setSize("200px", "200px");
// show drag over effect
target.addDragOverHandler(new DragOverHandler() {
@Override
public void onDragOver(DragOverEvent event) {
target.getElement().getStyle().setBackgroundColor("#ffa");
}
});
// clear drag over effect
target.addDragLeaveHandler(new DragLeaveHandler() {
@Override
public void onDragLeave(DragLeaveEvent event) {
target.getElement().getStyle().clearBackgroundColor();
}
});
// enable as drop target
target.addDropHandler(new DropHandler() {
@Override
public void onDrop(DropEvent event) {
event.preventDefault();
// not sure if the calculation is right, didn't test it really
int x = (event.getNativeEvent().getClientX() - target.getAbsoluteLeft()) + Window.getScrollLeft();
int y = (event.getNativeEvent().getClientY() - target.getAbsoluteTop()) + Window.getScrollTop();
target.getElement().getStyle().clearBackgroundColor();
Window.alert("x: " + x + ", y:" + y);
// add image with same URL as the dropped one to absolute panel at given coordinates
target.add(new Image(event.getData("text")), x, y);
}
});
RootPanel.get().add(image);
RootPanel.get().add(target);
}
这里是自定义面板
public class DropAbsolutePanel extends AbsolutePanel implements HasDropHandlers, HasDragOverHandlers,
HasDragLeaveHandlers {
@Override
public HandlerRegistration addDropHandler(DropHandler handler) {
return addBitlessDomHandler(handler, DropEvent.getType());
}
@Override
public HandlerRegistration addDragOverHandler(DragOverHandler handler) {
return addBitlessDomHandler(handler, DragOverEvent.getType());
}
@Override
public HandlerRegistration addDragLeaveHandler(DragLeaveHandler handler) {
return addBitlessDomHandler(handler, DragLeaveEvent.getType());
}
}
和图像类:
public class DragImage extends Image {
public DragImage() {
super();
initDnD();
}
private void initDnD() {
// enables dragging if browser supports html5
getElement().setDraggable(Element.DRAGGABLE_TRUE);
addDragStartHandler(new DragStartHandler() {
@Override
public void onDragStart(DragStartEvent event) {
// attach image URL to drag data
event.setData("text", getUrl());
}
});
}
}