title: ImageIcon click and drag around the window
body: <p>I'm trying to make it so I can click and drag an ImageIcon (in this case a card image but I'd like to learn how to do it generally) around the window but I don't really know how. I would like to be able to click and hold the mouse botton, drag the ImageIcon, and have stay where it is whn I release the mouse botton. </p>
  
  <p>This is the code I have so far:</p>
  
  <pre><code>import javax.swing.*;
  import java.awt.*;
  import java.awt.event.MouseAdapter;
  import java.awt.event.MouseEvent;
  import java.awt.event.MouseListener;
  
  public class MyFirstClass 
  {
  
      public static void main(String[] args)
      {
          //load the card image from the gif file.
          final ImageIcon cardIcon = new ImageIcon("cardImages/tenClubs.gif");
          JLabel lbl = new JLabel(cardIcon);
          //create a panel displaying the card image
          JPanel panel = new JPanel()
          {
              //paintComponent is called automatically by the JRE whenever
              //the panel needs to be drawn or redrawn
              public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  cardIcon.paintIcon(this, g, 20, 20);
              }
          };
  
          lbl.setTransferHandler(null);
          MouseListener listener = new MouseAdapter() {
            public void mousePressed(MouseEvent me) {
              JComponent comp = (JComponent) me.getSource();
              TransferHandler handler = comp.getTransferHandler();
              handler.exportAsDrag(comp, me, TransferHandler.COPY);
            }
          };
          lbl.addMouseListener(listener);
  
          //create &amp; make visible a JFrame to contain the panel
          JFrame window = new JFrame("Cards");
          window.add(panel);
          window.setPreferredSize(new Dimension(200,200));
          window.pack();
          window.setVisible(true);
      }
  }
  </code></pre>
  
  <p>Thank you.</p>