GWT: capturing mouse position, drag and drop

posted on June 20, 2009 in coding

If you need to use drag and drop in your GWT application, there is a wonderful library available: gwt-dnd. Check out the demo: it offers almost everything one might expect from drag&drop.
Sometimes though, such a vast and feature-rich library is too much. I needed to create a custom scrollbar, and to do this with gwt-dnd is not that simple, since its constraint panel only affects the dropzone while the draggable element can still be dragged anywhere in the main AbsolutePanel.
So I looked for another way, and in fact it isn’t hard at all:

1. GWT 1.6 introduced a new way to capture mouse movement and any other native DOM event.

1
2
3
4
5
6
7
8
9
Event.addNativePreviewHandler(new NativePreviewHandler(){
	public void onPreviewNativeEvent(NativePreviewEvent event) {
		if (event.getNativeEvent().getType().equals("mousemove"))
		{
			int xCoord = event.getNativeEvent().getClientX();
			int yCoord = event.getNativeEvent().getClientY();
		}
	}
});

2. Implementing drag&drop brings another problem: only elements that are children of an AbsolutePanel can be moved, with the function setWidgetPosition(). As a result your object can only be dragged within this AbsolutePanel. This can be overcome (although I’m afraid it’s not best practice) by using DOM.setStyleAttribute:

1
2
3
4
5
6
7
8
9
10
11
12
Event.addNativePreviewHandler(new NativePreviewHandler(){
	public void onPreviewNativeEvent(NativePreviewEvent event) {
		if (event.getNativeEvent().getType().equals("mousemove"))
		{
			if (dragging == true)			{
				DOM.setStyleAttribute(dragObject.getElement(), "left", (dragObject.getElement().getAbsoluteLeft() + event.getNativeEvent().getClientX()) + "px");
				DOM.setStyleAttribute(dragObject.getElement(), "top", (dragObject.getElement().getAbsoluteTop() + event.getNativeEvent().getClientY()) + "px")
			}
		}
	}
});

Put a handler on your object which defines dragging, and add a ‘dragging = false’ to the mouseup event, and there it is: basic drag and drop.

2 Comments »

  1. Got the source for the custom scrollbar?

    Comment by Brett — June 25, 2009 @ 2:08 pm

  2. Not yet, it needs some refactoring and is part of a custom scrollPanel that allows iPhone-like scrolling. I don’t want to release it without the refactoring/testing in place. But with the code above, it’s really not hard to create a custom scrollbar yourself.

    Comment by Maarten — June 25, 2009 @ 2:39 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

-->

Blom Inrichtingen - interieurprojecten in de gezondheidszorg