Adding Image-Dragging Behavior : Drag Drop « Swing JFC « Java






Adding Image-Dragging Behavior

  
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Image;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.TransferHandler;

public class DragImage {

  public static void main(String args[]) {

    JFrame frame = new JFrame("Clip Image");
    Container contentPane = frame.getContentPane();

    final Clipboard clipboard = frame.getToolkit().getSystemClipboard();

    Icon icon = new ImageIcon("jaeger.jpg");
    final JLabel label = new JLabel(icon);
    label.setTransferHandler(new ImageSelection());

    MouseListener mouseListener = new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        JComponent comp = (JComponent) e.getSource();
        TransferHandler handler = comp.getTransferHandler();
        handler.exportAsDrag(comp, e, TransferHandler.COPY);
      }
    };
    label.addMouseListener(mouseListener);

    JScrollPane pane = new JScrollPane(label);
    contentPane.add(pane, BorderLayout.CENTER);

    JButton copy = new JButton("Copy");
    copy.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        TransferHandler handler = label.getTransferHandler();
        handler.exportToClipboard(label, clipboard,
            TransferHandler.COPY);
      }
    });

    JButton clear = new JButton("Clear");
    clear.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        label.setIcon(null);
      }
    });
    clear.setTransferHandler(new TransferHandler("text"));
    mouseListener = new MouseAdapter() {
      public void mousePressed(MouseEvent e) {
        JComponent comp = (JComponent) e.getSource();
        TransferHandler handler = comp.getTransferHandler();
        handler.exportAsDrag(comp, e, TransferHandler.COPY);
      }
    };
    clear.addMouseListener(mouseListener);

    JButton paste = new JButton("Paste");
    paste.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Transferable clipData = clipboard.getContents(clipboard);
        if (clipData != null) {
          if (clipData.isDataFlavorSupported(DataFlavor.imageFlavor)) {
            TransferHandler handler = label.getTransferHandler();
            handler.importData(label, clipData);
          }
        }
      }
    });

    JPanel p = new JPanel();
    p.add(copy);
    p.add(clear);
    p.add(paste);
    contentPane.add(p, BorderLayout.SOUTH);

    JTextField tf = new JTextField();
    tf.setDragEnabled(true);
    contentPane.add(tf, BorderLayout.NORTH);
    frame.setSize(300, 300);
    frame.show();
  }
}

class ImageSelection extends TransferHandler implements Transferable {

  private static final DataFlavor flavors[] = { DataFlavor.imageFlavor };

  private JLabel source;

  private Image image;

  public int getSourceActions(JComponent c) {
    return TransferHandler.COPY;
  }

  public boolean canImport(JComponent comp, DataFlavor flavor[]) {
    if (!(comp instanceof JLabel)) {
      return false;
    }
    for (int i = 0, n = flavor.length; i < n; i++) {
      for (int j = 0, m = flavors.length; j < m; j++) {
        if (flavor[i].equals(flavors[j])) {
          return true;
        }
      }
    }
    return false;
  }

  public Transferable createTransferable(JComponent comp) {
    // Clear
    source = null;
    image = null;

    if (comp instanceof JLabel) {
      JLabel label = (JLabel) comp;
      Icon icon = label.getIcon();
      if (icon instanceof ImageIcon) {
        image = ((ImageIcon) icon).getImage();
        source = label;
        return this;
      }
    }
    return null;
  }

  public boolean importData(JComponent comp, Transferable t) {
    if (comp instanceof JLabel) {
      JLabel label = (JLabel) comp;
      if (t.isDataFlavorSupported(flavors[0])) {
        try {
          image = (Image) t.getTransferData(flavors[0]);
          ImageIcon icon = new ImageIcon(image);
          label.setIcon(icon);
          return true;
        } catch (UnsupportedFlavorException ignored) {
        } catch (IOException ignored) {
        }
      }
    }
    return false;
  }

  // Transferable
  public Object getTransferData(DataFlavor flavor) {
    if (isDataFlavorSupported(flavor)) {
      return image;
    }
    return null;
  }

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

  public boolean isDataFlavorSupported(DataFlavor flavor) {
    return flavor.equals(DataFlavor.imageFlavor);
  }
}


           
         
    
  








Related examples in the same category

1.Tree: Drag and DropTree: Drag and Drop
2.Drag and dropDrag and drop
3.Dropper - show File Drop Target from Drag-n-DropDropper - show File Drop Target from Drag-n-Drop
4.Demonstrate various aspects of Swing data transferDemonstrate various aspects of Swing data transfer
5.File Tree Drop TargetFile Tree Drop Target
6.File Tree Drag SourceFile Tree Drag Source
7.Editor Drop Target 4Editor Drop Target 4
8.Drag Drop Tree ExampleDrag Drop Tree Example
9.JLabel Drag Source JLabel Drag Source
10.Panel Drop TargetPanel Drop Target
11.Editor Drop Target 3Editor Drop Target 3
12.Editor Drop TargetEditor Drop Target
13.Editor Drop Target 2Editor Drop Target 2
14.JTextArea subclass allows TransferableColor objects toJTextArea subclass allows TransferableColor objects to
15.Transferable Color
16.Color Drag Source
17.A sample component for dragging and dropping a collection of files into a tree.A sample component for dragging and dropping a collection of files into a tree.
18.Test of the DragGesture classes and JList to see if weTest of the DragGesture classes and JList to see if we
19.A TransferHandler and JTextArea that will accept any drop at allA TransferHandler and JTextArea that will accept any drop at all
20.Drag and drop: TextAreaDrag and drop: TextArea
21.Drag capabilities: JListDrag capabilities: JList
22.A simple drop tester application for JDK 1.4 Swing componentsA simple drop tester application for JDK 1.4 Swing components
23.Drag and Drop:JList and ListDrag and Drop:JList and List
24.DnD (drag and drop)JTree code DnD (drag and drop)JTree code
25.Drop: TextAreaDrop: TextArea
26.Drag and drop: TextArea 2Drag and drop: TextArea 2
27.Label DnD (Drag and Drop) Label DnD (Drag and Drop)
28.LabelDnD2 allows dropping color onto the foreground of the JLabelLabelDnD2 allows dropping color onto the foreground of the JLabel
29.Drag List Demo Drag List Demo
30.Drag Picture Demo
31.Extended DnD (Drag and Drop) DemoExtended DnD (Drag and Drop) Demo
32.Drag Color DemoDrag Color Demo
33.Drag File DemoDrag File Demo
34.Drag Picture Demo 2
35.Drag Color TextField DemoDrag Color TextField Demo
36.BasicDnD (Drag and Drop)BasicDnD (Drag and Drop)
37.Drag and drop icons: use an icon property.
38.Implement drag & drop functionality in your application
39.Detect a drag initiating gesture in your application
40.Making a Component Draggable
41.Getting and Setting Text on the System Clipboard
42.Use drag and drop to reorder a list
43.Create a drag source a drop target and a transferable object.
44.implements DragGestureListener, Transferable
45.Comma separated text will be inserted into two or more rows.
46.TransferHandler subclass wraps another TransferHandler and delegates most of its operations to the wrapped handler
47.Setting text drag in a JTextArea
48.Built-in drag and drop support: utilize a TransferHandler class
49.This program demonstrates drag and drop in an image list.
50.This program demonstrates the basic Swing support for drag and drop.