Things To Remember: GWT Drag and Drop Edition

So I wrote the following code and wired it into the mouse up, down and move listeners so I can do drag and drop:

		@Override
		public void onMouseUp(MouseUpEvent event)
		{
			isDragging = false;
			// Do something to indicate we're done dragging
			
			DOM.releaseCapture(fClickLayer.getElement());
		}
		
		@Override
		public void onMouseMove(MouseMoveEvent event)
		{
			if (isDragging) {
				// Do something with the event to drag
			}
		}

		@Override
		public void onMouseDown(MouseDownEvent event)
		{
			DOM.setCapture(fClickLayer.getElement());
			// Note the initial state to start dragging
		}

And of course after the first three move events I stopped receiving move events, but instead the widget would be selected.

After banging my head against a brick wall for a couple of hours I realized I needed to prevent the browser from taking the default behavior on the received click and move events. And that’s done with the preventDefault() method:

		@Override
		public void onMouseUp(MouseUpEvent event)
		{
			isDragging = false;
			// Do something to indicate we're done dragging
			
			DOM.releaseCapture(fClickLayer.getElement());
		}
		
		@Override
		public void onMouseMove(MouseMoveEvent event)
		{
			if (isDragging) {
				event.preventDefault();		// ADD ME HERE
				// Do something with the event to drag
			}
		}

		@Override
		public void onMouseDown(MouseDownEvent event)
		{
			DOM.setCapture(fClickLayer.getElement());
			event.preventDefault();		// ADD ME HERE
			// Note the initial state to start dragging
		}

Duh.

As an aside, here’s a snippet of code that you can use to prevent something from being selected in HTML. You can also do this in CSS, I suppose. I encountered this snippet of code here.

	private native static void disableSelectInternal(Element e, boolean disable) 
	/*-{
    	if (disable) {
        	e.ondrag = function () { return false; };
        	e.onselectstart = function () { return false; };
        	e.style.MozUserSelect="none"
    	} else {
        	e.ondrag = null;
        	e.onselectstart = null;
        	e.style.MozUserSelect="text"
    	}
	}-*/;

I first tried hooking this up to the class receiving the mouse events, but to no avail.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s