?
Solved

Drag and Drop an Image

Posted on 2005-04-25
13
Medium Priority
?
305 Views
Last Modified: 2012-08-13
Hello;

I have a frame w/ a panel w/c has 2 label's on it. I'm trying to drag and drop the image to the right so that it can transfer the image but will erase the image on its left. Like simple cut and paste senario. This are my codes and hoping some one can help :

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ImageTransfer extends JFrame  {
      
      private JPanel panel1;
      private JLabel label1;
      private JLabel label2;

      public ImageTransfer() {
            
            super("Drag & Drop");
            
            panel1 = new JPanel();
            panel1.setLayout(new GridLayout(1,2));
            
            label1 = new JLabel();
            label2 = new JLabel();
            
            label1.setIcon(new ImageIcon("Image1.gif"));
            label2.setIcon(new ImageIcon("Image2.gif"));
            
            panel1.add(label1);
            panel1.add(label2);
            
        DragSource dragSource = DragSource.getDefaultDragSource();
        dragSource.createDefaultDragGestureRecognizer(this,
                    DnDConstants.ACTION_COPY_OR_MOVE,
                        new LabelDragListener( label1, label2 ) );
       
        DropTarget dropTarget = new DropTarget(this, new LabelDropListener( label2 ) );
        dropTarget.setDefaultActions(DnDConstants.ACTION_COPY_OR_MOVE);
            
            getContentPane().add(panel1, BorderLayout.CENTER);
        setSize( 300, 100 );
        setVisible( true );
      }

      public static void main(String[] args) {
            ImageTransfer x = new ImageTransfer();
            x.setDefaultCloseOperation( EXIT_ON_CLOSE );
      }
}

class LabelDragListener implements DragGestureListener {
      
      private JLabel parentPanel;
      private JLabel childPanel;

      public LabelDragListener(JLabel p, JLabel c) {
            parentPanel = p;
            childPanel = c;
      }

      public void dragGestureRecognized(DragGestureEvent dge) {

            dge.startDrag(null, new LabelSelection(childPanel));
            parentPanel.remove(childPanel);
            parentPanel.validate();
            parentPanel.repaint();
      }
}

class LabelDropListener implements DropTargetListener {
      
      private JLabel dropPanel;
      public final static DataFlavor PANEL_FLAVOR = new DataFlavor(JLabel.class, "JLabel Instances");
      
      LabelDropListener(JLabel p) {
            dropPanel = p;
      }

      public void dragExit(DropTargetEvent dte) {}

      public void dragEnter(DropTargetDragEvent dtde) {
            
            if (dtde.isDataFlavorSupported(PANEL_FLAVOR)) {
                  dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
            }
      }

      public void dragOver(DropTargetDragEvent dtde) {}

      public void dropActionChanged(DropTargetDragEvent dtde) {}

      public void drop(DropTargetDropEvent dtde) {
            if (dtde.isDataFlavorSupported(PANEL_FLAVOR)) {
                  try {
                        JLabel panel = (JLabel) dtde.getTransferable()
                                    .getTransferData(PANEL_FLAVOR);
                        dropPanel.setIcon(dropPanel.getIcon());
                        dropPanel.validate();
                        dropPanel.repaint();
                        
                  } catch (Exception exc) {
                        exc.printStackTrace();
                  }
            }
      }
}

class LabelSelection implements Transferable {
      
      public final DataFlavor PANEL_FLAVOR = new DataFlavor(JLabel.class,
                  "JLabel Instances");

      private DataFlavor[] flavors = { PANEL_FLAVOR };
      protected JLabel panel;

      public LabelSelection(JLabel pnl) {
            panel = pnl;
      }

      public DataFlavor[] getTransferDataFlavors() {
            return flavors;
      }

      public boolean isDataFlavorSupported(DataFlavor flavor) {
            for (int i = 0; i < flavors.length; i++) {
                  if (flavors[i].equals(flavor)) {
                        return true;
                  }
            }
            return false;
      }

      public Object getTransferData(DataFlavor flavor)
                  throws UnsupportedFlavorException, IOException {
            if (flavor.equals(PANEL_FLAVOR)) {
                  return panel;
            }
            throw new UnsupportedFlavorException(flavor);
      }
}
 
0
Comment
Question by:simple21
  • 6
  • 5
12 Comments
 
LVL 17

Expert Comment

by:Dejan Pažin
ID: 13857361


If all you need is transfer of icons from one label to another, here is a much shorter example:


import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;


import javax.swing.*;

public class ImageTransfer extends JFrame
{

   private JPanel panel1;
   private JLabel label1;
   private JLabel label2;

   public ImageTransfer()
   {
      super("Drag & Drop");

      panel1 = new JPanel();
      panel1.setLayout(new GridLayout(1, 2));

      label1 = new JLabel();
      label2 = new JLabel();

      label1.setIcon(new ImageIcon("Image1.gif"));
      label2.setIcon(new ImageIcon("Image2.gif"));

      panel1.add(label1);
      panel1.add(label2);
      label1.setTransferHandler(new TransferHandler("icon"));
      label1.addMouseListener(new DragMouseAdapter());
      label2.setTransferHandler(new TransferHandler("icon"));
      label2.addMouseListener(new DragMouseAdapter());
      getContentPane().add(panel1, BorderLayout.CENTER);
      setSize(300, 100);
      setVisible(true);
   }

   public static void main(String[] args)
   {
      ImageTransfer x = new ImageTransfer();
      x.setDefaultCloseOperation(EXIT_ON_CLOSE);
   }
}


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

Expert Comment

by:Dejan Pažin
ID: 13857644

The above example only makes copy, and here is how to do a move operation (that way the label where you drag from loses the icon):



import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;

import javax.swing.*;

public class ImageTransfer extends JFrame
{

   private JPanel panel1;
   private JLabel label1;
   private JLabel label2;

   public ImageTransfer()
   {
      super("Drag & Drop");

      panel1 = new JPanel();
      panel1.setLayout(new GridLayout(1, 2));

      label1 = new JLabel();
      label2 = new JLabel();

      label1.setIcon(new ImageIcon("Image1.gif"));
      label2.setIcon(new ImageIcon("Image2.gif"));

      panel1.add(label1);
      panel1.add(label2);
      label1.setTransferHandler(new MyTransferHandler("icon"));
      label1.addMouseListener(new DragMouseAdapter());
      label2.setTransferHandler(new MyTransferHandler("icon"));
      label2.addMouseListener(new DragMouseAdapter());

      getContentPane().add(panel1, BorderLayout.CENTER);
      setSize(300, 100);
      setVisible(true);
   }

   public static void main(String[] args)
   {
      ImageTransfer x = new ImageTransfer();
      x.setDefaultCloseOperation(EXIT_ON_CLOSE);
   }

   private class MyTransferHandler extends TransferHandler
   {
      public MyTransferHandler(String property)
      {
         super(property);
      }

      protected void exportDone(JComponent source, Transferable data, int action)
      {        
         super.exportDone(source, data, action);
         ((JLabel)source).setIcon(null);
      }
   }

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

Author Comment

by:simple21
ID: 13863975
It replaces the previous one great and returns to its position but
if I use a for statement when you put it back to its original it disappears ? how can this be solved thanks :

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;

import javax.swing.*;

public class ImageTransfer extends JFrame
{

   private JPanel panel1;
   private JPanel panel2;
   private JLabel label1;
   private JLabel label2;

   public ImageTransfer()
   {
      super("Drag & Drop");

      panel1 = new JPanel();
      panel2 = new JPanel();
      panel1.setLayout(new GridLayout(1, 2));

      label1 = new JLabel();
      label2 = new JLabel();

      for (int i=0; i<2; i++) {

            panel1.add(panel2);

            if (i==0) {

            panel2.add(label1);
                  label1.setIcon(new ImageIcon("Image1.gif"));
                  label1.setTransferHandler(new MyTransferHandler("icon"));
                  label1.addMouseListener(new DragMouseAdapter());

            } else if (i==1) {
            panel2.add(label2);
                  label2.setIcon(new ImageIcon("Image2.gif"));
                  label2.setTransferHandler(new MyTransferHandler("icon"));
                  label2.addMouseListener(new DragMouseAdapter());
            }
      }

      getContentPane().add(panel1, BorderLayout.CENTER);
      setSize(300, 100);
      setVisible(true);
   }

   public static void main(String[] args)
   {
      ImageTransfer x = new ImageTransfer();
      x.setDefaultCloseOperation(EXIT_ON_CLOSE);
   }

   private class MyTransferHandler extends TransferHandler
   {
      public MyTransferHandler(String property)
      {
         super(property);
      }

      protected void exportDone(JComponent source, Transferable data, int action)
      {        
         super.exportDone(source, data, action);
         ((JLabel)source).setIcon(null);
      }
   }

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

      
      
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:simple21
ID: 13863978
I need to handle a for statement.
0
 
LVL 17

Expert Comment

by:Dejan Pažin
ID: 13864651

I am not sure what you want to achieve with the for statement, but code you posted is not good. In your for statement you are adding the same jpanel over and over and the same label to that panel. That is wrong, you should create new component each time you want to add it to a container.

Here is an example, I dont know if this is exactly what you wanted, but it shows you how to add more components to a container in a for statement


import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;

import javax.swing.*;
import javax.swing.border.EtchedBorder;

public class ImageTransfer extends JFrame
{

   private String icons[] = new String[]{"Image1.gif", "Image2.gif"};

   public ImageTransfer()
   {
      super("Drag & Drop");

      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(2, 2));

      for (int i = 0; i < 4; i++)
      {
         JLabel label = new JLabel(new ImageIcon(icons[i % 2]));
         label.setBorder(new EtchedBorder());
         panel.add(label);
         label.setTransferHandler(new MyTransferHandler("icon"));
         label.addMouseListener(new DragMouseAdapter());
      }

      getContentPane().add(panel, BorderLayout.CENTER);
      setSize(300, 100);
      setVisible(true);
   }

   public static void main(String[] args)
   {
      ImageTransfer x = new ImageTransfer();
      x.setDefaultCloseOperation(EXIT_ON_CLOSE);
   }

   private class MyTransferHandler extends TransferHandler
   {
      public MyTransferHandler(String property)
      {
         super(property);
      }

      protected void exportDone(JComponent source, Transferable data, int action)
      {        
         super.exportDone(source, data, action);
         ((JLabel) source).setIcon(null);
      }
   }

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

Author Comment

by:simple21
ID: 13864760
> In your for statement you are adding the same jpanel over and over and the same label to that panel. That is wrong.

I need another panel to add to another panel in a for statement and while looping I need to be able to add the label to that panel.

Its like I'm placing several boxes of panel inside a panel then add the labels in that boxes ? reason I need to colorized the panel of boxes which I'm adding to the main panel.
0
 

Author Comment

by:simple21
ID: 13864790
My labels are transparent and the panels has several colors so as you can see my example codes above shows it all.
0
 
LVL 17

Expert Comment

by:Dejan Pažin
ID: 13864834

Here is a more colorful example. Is this what you needed?


import java.awt.*;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;

import javax.swing.*;
import javax.swing.border.EtchedBorder;

public class ImageTransfer extends JFrame
{

   private String icons[] = new String[]{"Image1.gif", "Image2.gif"};

   private Color colors[] = new Color[]{Color.red, Color.green,  Color.yellow, Color.blue};


   public ImageTransfer()
   {
      super("Drag & Drop");

      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(2, 2));

      for (int i = 0; i < 4; i++)
      {
         JLabel label = new JLabel(new ImageIcon(icons[i % 2]));
         label.setBorder(new EtchedBorder());
         label.setBackground(colors[i]);
         label.setOpaque(true);
         panel.add(label);
         label.setTransferHandler(new MyTransferHandler("icon"));
         label.addMouseListener(new DragMouseAdapter());
      }

      getContentPane().add(panel, BorderLayout.CENTER);
      setSize(300, 100);
      setVisible(true);
   }

   public static void main(String[] args)
   {
      ImageTransfer x = new ImageTransfer();
      x.setDefaultCloseOperation(EXIT_ON_CLOSE);
   }

   private class MyTransferHandler extends TransferHandler
   {
      public MyTransferHandler(String property)
      {
         super(property);
      }

      protected void exportDone(JComponent source, Transferable data, int action)
      {
         super.exportDone(source, data, action);
         ((JLabel) source).setIcon(null);
      }
   }

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

Author Comment

by:simple21
ID: 13864839
The codes from :

Comment from simple21
Date: 04/25/2005 09:06PM PDT

Is what I'm using if you can solve this, then that will be the final
since this is the current problem, I'm facing. Thanks a lot.
0
 

Author Comment

by:simple21
ID: 13864855
I'm creating a new game which looks like a chess but not really
a chess I just copied the chessboard colors. Thats why I added
a JPanel to another JPanel and in the loop I added the colors for the board. If you work on my codes that will be it.
0
 
LVL 17

Expert Comment

by:Dejan Pažin
ID: 13865101

I think this will be the solution you need. The labels are colored and the image does not disappear if you drag it back to where you started the draging.

import java.awt.*;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;

import javax.swing.*;
import javax.swing.border.EtchedBorder;

public class ImageTransfer extends JFrame
{

   private String icons[] = new String[]{"Image1.gif", "Image2.gif"};
   private Color colors[] = new Color[]{Color.red, Color.green,  Color.yellow, Color.blue};

   public ImageTransfer()
   {
      super("Drag & Drop");

      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(2, 2));

      MyTransferHandler transferHandler = new MyTransferHandler("icon");
      for (int i = 0; i < 4; i++)
      {
         JLabel label = new JLabel(new ImageIcon(icons[i % 2]));
         label.setBorder(new EtchedBorder());
         label.setBackground(colors[i]);
         label.setOpaque(true);
         panel.add(label);
         label.setTransferHandler(transferHandler);
         label.addMouseListener(new DragMouseAdapter());
      }

      getContentPane().add(panel, BorderLayout.CENTER);
      setSize(300, 100);
      setVisible(true);
   }

   public static void main(String[] args)
   {
      ImageTransfer x = new ImageTransfer();
      x.setDefaultCloseOperation(EXIT_ON_CLOSE);
   }

   private class MyTransferHandler extends TransferHandler
   {
      private JComponent importedInto;
      public MyTransferHandler(String property)
      {
         super(property);
      }

      protected void exportDone(JComponent source, Transferable data, int action)
      {
         if (importedInto == source) return;
         ((JLabel)source).setIcon(null);
         super.exportDone(source, data, action);
      }

      public boolean importData(JComponent comp, Transferable t)
      {
         importedInto = comp;
         return super.importData(comp, t);
      }
   }

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

Accepted Solution

by:
PashaMod earned 0 total points
ID: 14238620
Closed, 325 points refunded.
Modname
Community Support Moderator
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month16 days, 4 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question