Share on Google+Share on Google+

Java Swing drag image

In this section, you will learn how to drag an image from one panel to another.

Java Swing drag image

Java Swing provides several classes that will allows us to drag and drop components(drop down list, text area, check box, radio button ,label, text field etc.) from one frame to another frame. Here we are going to drag an image from one panel to another. For this, we have used two images. One image to drag and another one should be blank image. The class TransferHandler allows us to transfer the image. The method exportAsDrag() of this class provides drag support. We have used MouseListener class to call all these functions. As the user pressed the mouse on the image from panel1 and released it on another one, the image will get displayed on panel2.

Here is the code:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class DragMouseAdapter extends MouseAdapter {
	public void mousePressed(MouseEvent e) {
		JComponent c = (JComponent) e.getSource();
		TransferHandler handler = c.getTransferHandler();
		handler.exportAsDrag(c, e, TransferHandler.COPY);

public class test1 {
	public static void main(String[] args) {
		JFrame f = new JFrame("Drag & Drop");
		ImageIcon icon1 = new ImageIcon("C:\\node.jpg");
		ImageIcon icon2 = new ImageIcon("C:\\blank.gif");
		JPanel panel = new JPanel(new GridLayout(2, 1));
		JPanel panel1 = new JPanel(new BorderLayout());
		JPanel panel2 = new JPanel();
		JLabel label1 = new JLabel(icon1);
		JLabel label2 = new JLabel(icon2);
		MouseListener listener = new DragMouseAdapter();
		label1.setTransferHandler(new TransferHandler("icon"));
		label2.setTransferHandler(new TransferHandler("icon"));
		f.setLayout(new GridLayout(1, 2));
		f.setSize(300, 400);


On dragging the image from panel1 to panel2, you will see that the same image will get displayed on panel2:


Posted on: May 6, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null