Java Swing drag image


 

Java Swing drag image

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

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();
		panel1.setBackground(Color.red);
		panel2.setBackground(Color.white);
		JLabel label1 = new JLabel(icon1);
		JLabel label2 = new JLabel(icon2);
		MouseListener listener = new DragMouseAdapter();
		label1.addMouseListener(listener);
		label2.addMouseListener(listener);
		label1.setTransferHandler(new TransferHandler("icon"));
		label2.setTransferHandler(new TransferHandler("icon"));
		panel1.add(label1);
		panel2.add(label2);
		panel.add(panel1);
		panel.add(panel2);
		f.setLayout(new GridLayout(1, 2));
		f.setSize(300, 400);
		f.add(panel);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);
	}
}

Output:

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

Ads