Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to drag and drop in Java

In this article we will see the process to do drag and drop in java going step by step making use of HTML elements.

The Java Drag and Drop API allow us to write code where the user can drag JComponents and drop them (or their attributes) onto another JComponent. The basis of the Drag and Drop API is the TransferHandler class. to grab.

It is recommended that you develop locally in a single file. Keep it simple, because it's easier to see the rad.

There are some tools we're going to use to make our HTML come to life:

  • Mouse events: mousedown, mouseup, mousemove
  • Document event object: (e)
  • DOM element position attributes

Drag & drop means a few different things to UI developers. Here are some examples of how drag & drop is used on the web today:

  • Drag an icon/image around the screen and drop it onto something
  • Drag content around to navigate through it
  • Drag a handle around to navigate through content

Let us focus on a 'click (mouse down) to start dragging', 'let go (mouse up) to stop dragging' pattern.

Basic Dragging & Dropping

First thing is to create an HTML element that we can drag around (drop it in your <body>).

Listing 1: Illustrates the HTML element

<div style="position:absolute;height:50px;width:50px;background-color:orange;cursor:pointer;" id="target"> </div>

Create a reference to use at document load:

Listing 2: Creating reference

$(function() { 
    var target = $('#target') 
})

By storing the lookup in a variable, we can save the browser from having to look it up every time we use it.

Listing 3: Storing lookup in a variable

$(function() { }) is a jQuery shortcut for $(document).ready(function() { })

We want the #target to react when the mouse interacts with it. We can do so by assigning actions to the different mouse events. Here's our template for creating this interaction:

Listing 4: Template to create actions

target.mousedown( function() { } )
$(document).mouseup( function() { } )
$(document).mousemove( function(e) { } )

They're called anonymous functions; they can be useful, but are lame in excess. Also, where did that (e) come from? This is an isolated incident. The e here represents an event object. It's created when an event is triggered, and we can get ahold of it through our anonymous function. It's optional, and we're opting in.

We are going to use the mouse events to determine what's going on in the browser. In this case, we're going to assume two things:

If the mouse is clicked down on our #target, then the user is going to start dragging the #target

If the mouse is un-clicked (mouseup) anywhere on our document, then the user is probably done dragging #target

Here's how it's done:

Listing 5: Using the mouse events

var dragging = false 	// set a global 'dragging' flag

target.mousedown(function() {
 	dragging = true 
})

$(document).mouseup(function() { 
	dragging = false 
})

$(document).mousemove( function(e) { } )

Now we're ready to make the created thing work for us. All of our decision-making is going to take place in the 'mousemove' event.

The assumption is that if a user has clicked on #target, then moved their mouse, that a drag is in order. Let's do that.

Listing 6: Moving the mouse on accessing the #target

$(document).mousemove( function(e) {
	if(dragging) {
		target.css('left', e.pageX)
		target.css('top', e.pageY)
	}
})

Java also provides multiple ways to drag component from one location and drop it to another location. Some basic components such as JTable, JList, JColorChooser, JTextArea, JTextField, JTextPane, etc have drag behavior by default. In those kind of components what we have to do is simply enable drag feature by usingsetDragEnabled(boolean b) method.

But when it comes to images Java does not provide such a method to associate drag behavior with an image. So, how we add drag behavior to an image?

One can:

  • Simply use MouseListeners (i.e. MouseMotionListener interface)
  • By using java.awt.dnd package and associated classes with it
  • Associate image with JLabel as Icon and drag label

Creating a desktop application that allows users to drag and drop files or other data formats to the application is not only cool, but could be really user friendly as well. Implementing this feature in Java is quite easy as well.

This is done by connecting an AWT Component to a DropTargetListener, using a DropTarget. Below is a brief code example on how this could be done.

First of all we create a simple JFrame which contains a JLabel.

Simple JFrame which contains a JLabel

Figure 1: Simple JFrame which contains a JLabel

Listing 7: Creating a JFrame

public class DragDropTestFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    public static void main(String[] args) {
        // Create our frame
        new DragDropTestFrame();
    }
    public DragDropTestFrame() {
        // Set the frame title
        super("Drag and drop test");
        // Set the size
        this.setSize(250, 150);
        // Create the label
        JLabel myLabel = new JLabel("Drag something here!", SwingConstants.CENTER);
        // Create the drag and drop listener
        MyDragDropListener myDragDropListener = new MyDragDropListener();
        // Connect the label with a drag and drop listener
        new DropTarget(myLabel, myDragDropListener);
        // Add the label to the content
        this.getContentPane().add(BorderLayout.CENTER, myLabel);
        // Show the frame
        this.setVisible(true);
    }

Secondly we create a new instance of our DropTargetListener, and connect it to our label via DropTarget.

Listing 8: Creating new instance of DropTargetListener

        // Create the drag and drop listener
        MyDragDropListener myDragDropListener = new MyDragDropListener();

        // Connect the label with a drag and drop listener
        new DropTarget(myLabel, myDragDropListener);

Afterwards we implement our MyDragDropListener class.

Listing 9: Implementing the MyDragDropListener class

class MyDragDropListener implements DropTargetListener {
    @Override
    public void drop(DropTargetDropEvent event) {
        // Accept copy drops
        event.acceptDrop(DnDConstants.ACTION_COPY);
        // Get the transfer which can provide the dropped item data
        Transferable transferable = event.getTransferable();
        // Get the data formats of the dropped item
        DataFlavor[] flavors = transferable.getTransferDataFlavors();
        // Loop through the flavors
        for (DataFlavor flavor : flavors) {
            try {
                // If the drop items are files
                if (flavor.isFlavorJavaFileListType()) {
                    // Get all of the dropped files
                    List files = (List) transferable.getTransferData(flavor);
                    // Loop them through
                    for (File file : files) {
                        // Print out the file path
                        System.out.println("File path is '" + file.getPath() + "'.");
                    }
                }
            } catch (Exception e) {
                // Print out the error stack
                e.printStackTrace();
            }
        }
        // Inform that the drop is complete
        event.dropComplete(true);
    }
    @Override
    public void dragEnter(DropTargetDragEvent event) {
    }
    @Override
    public void dragExit(DropTargetEvent event) {
    }
    @Override
    public void dragOver(DropTargetDragEvent event) {
    }
    @Override
    public void dropActionChanged(DropTargetDragEvent event) {
    }
}

Hope you liked the article, see you next time.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login