MimeClipboard Test : Drag Drop « Swing JFC « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Swing JFC » Drag DropScreenshots 
MimeClipboard Test
MimeClipboard Test
 

/**
 @version 1.10 1999-09-20
 @author Cay Horstmann
 */

import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FilterInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class MimeClipboardTest {
  public static void main(String[] args) {
    JFrame frame = new MimeClipboardFrame();
    frame.show();
  }
}

class MimeClipboardFrame extends JFrame implements ActionListener {
  public MimeClipboardFrame() {
    setSize(300300);
    setTitle("MimeClipboardTest");
    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

    Container contentPane = getContentPane();
    label = new JLabel();
    contentPane.add(label, "Center");

    JMenu fileMenu = new JMenu("File");
    openItem = new JMenuItem("Open");
    openItem.addActionListener(this);
    fileMenu.add(openItem);

    exitItem = new JMenuItem("Exit");
    exitItem.addActionListener(this);
    fileMenu.add(exitItem);

    JMenu editMenu = new JMenu("Edit");
    copyItem = new JMenuItem("Copy");
    copyItem.addActionListener(this);
    editMenu.add(copyItem);

    pasteItem = new JMenuItem("Paste");
    pasteItem.addActionListener(this);
    editMenu.add(pasteItem);

    JMenuBar menuBar = new JMenuBar();
    menuBar.add(fileMenu);
    menuBar.add(editMenu);
    setJMenuBar(menuBar);
  }

  public void actionPerformed(ActionEvent evt) {
    Object source = evt.getSource();
    if (source == openItem) {
      JFileChooser chooser = new JFileChooser();
      chooser.setCurrentDirectory(new File("."));

      chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public boolean accept(File f) {
          String name = f.getName().toLowerCase();
          return name.endsWith(".gif"|| name.endsWith(".jpg")
              || name.endsWith(".jpeg"|| f.isDirectory();
        }

        public String getDescription() {
          return "Image files";
        }
      });

      int r = chooser.showOpenDialog(this);
      if (r == JFileChooser.APPROVE_OPTION) {
        String name = chooser.getSelectedFile().getAbsolutePath();
        setImage(Toolkit.getDefaultToolkit().getImage(name));
      }
    else if (source == exitItem)
      System.exit(0);
    else if (source == copyItem)
      copy();
    else if (source == pasteItem)
      paste();
  }

  private void copy() {
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(theImage, 0);
    try {
      tracker.waitForID(0);
    catch (InterruptedException e) {
    }
    BufferedImage image = new BufferedImage(theImage.getWidth(null),
        theImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.drawImage(theImage, 00null);

    Bitmap bitmap = new Bitmap(image);
    SerializableSelection selection = new SerializableSelection(bitmap);
    mimeClipboard.setContents(selection, null);
  }

  private void paste() {
    Transferable selection = mimeClipboard.getContents(this);
    try {
      Bitmap bitmap = (Bitmapselection
          .getTransferData(SerializableSelection.serializableFlavor);
      setImage(bitmap.getImage());
    catch (Exception e) {
    }
  }

  public void setImage(Image image) {
    theImage = image;
    label.setIcon(new ImageIcon(image));
  }

  private static Clipboard mimeClipboard = new MimeClipboard(Toolkit
      .getDefaultToolkit().getSystemClipboard());

  private Image theImage;

  private JLabel label;

  private JMenuItem openItem;

  private JMenuItem exitItem;

  private JMenuItem copyItem;

  private JMenuItem pasteItem;
}

class Bitmap implements Serializable {
  public Bitmap(BufferedImage image) {
    type = image.getType();
    width = image.getWidth();
    height = image.getHeight();
    WritableRaster raster = image.getRaster();
    data = raster.getDataElements(00, width, height, null);
  }

  public BufferedImage getImage() {
    BufferedImage image = new BufferedImage(width, height, type);
    WritableRaster raster = image.getRaster();
    raster.setDataElements(00, width, height, data);
    return image;
  }

  private int type;

  private int width;

  private int height;

  private Object data;
}

class SerializableSelection implements Transferable {
  public SerializableSelection(Serializable object) {
    theObject = object;
  }

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

  public synchronized Object getTransferData(DataFlavor flavor)
      throws UnsupportedFlavorException {
    if (flavor.equals(serializableFlavor)) {
      return theObject;
    else {
      throw new UnsupportedFlavorException(flavor);
    }
  }

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

  public static final DataFlavor serializableFlavor = new DataFlavor(
      java.io.Serializable.class, "Serializable Object");

  private static DataFlavor[] flavors = serializableFlavor };

  private Serializable theObject;
}

class MimeClipboard extends Clipboard {
  public MimeClipboard(Clipboard cb) {
    super("MIME/" + cb.getName());
    clip = cb;
  }

  public synchronized void setContents(Transferable contents,
      ClipboardOwner owner) {
    if (contents instanceof SerializableSelection) {
      try {
        DataFlavor flavor = SerializableSelection.serializableFlavor;
        Serializable obj = (Serializablecontents
            .getTransferData(flavor);
        String enc = encode(obj);
        String header = "Content-type: " + flavor.getMimeType()
            "\nContent-length: " + enc.length() "\n\n";
        StringSelection selection = new StringSelection(header + enc);
        clip.setContents(selection, owner);
      catch (UnsupportedFlavorException e) {
      catch (IOException e) {
      }
    else
      clip.setContents(contents, owner);
  }

  public synchronized Transferable getContents(Object requestor) {
    Transferable contents = clip.getContents(requestor);

    if (contents instanceof StringSelection) {
      String data = null;
      try {
        data = (Stringcontents
            .getTransferData(DataFlavor.stringFlavor);
      catch (UnsupportedFlavorException e) {
        return contents;
      catch (IOException e) {
        return contents;
      }

      if (!data.startsWith("Content-type: "))
        return contents;
      int start = -1;
      // skip three newlines
      for (int i = 0; i < 3; i++) {
        start = data.indexOf('\n', start + 1);
        if (start < 0)
          return contents;
      }
      Serializable obj = decode(data.substring(start));
      SerializableSelection selection = new SerializableSelection(obj);
      return selection;
    else
      return contents;
  }

  public static String encode(Serializable obj) {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    try {
      Base64OutputStream b64Out = new Base64OutputStream(bOut);
      ObjectOutputStream out = new ObjectOutputStream(b64Out);
      out.writeObject(obj);
      out.close();
      return bOut.toString("8859_1");
    catch (IOException exception) {
      return null;
    }
  }

  public static Serializable decode(String s) {
    try {
      byte[] bytes = s.getBytes("8859_1");
      ByteArrayInputStream bIn = new ByteArrayInputStream(bytes);
      Base64InputStream b64In = new Base64InputStream(bIn);
      ObjectInputStream in = new ObjectInputStream(b64In);
      Object obj = in.readObject();
      in.close();
      return (Serializableobj;
    catch (Exception e) {
      return null;
    }
  }

  private Clipboard clip;
}

/*
 * BASE64 encoding encodes 3 bytes into 4 characters.
 * |11111122|22223333|33444444| Each set of 6 bits is encoded according to the
 * toBase64 map. If the number of input bytes is not a multiple of 3, then the
 * last group of 4 characters is padded with one or two = signs. Each output
 * line is at most 76 characters.
 */

class Base64OutputStream extends FilterOutputStream {
  public Base64OutputStream(OutputStream out) {
    super(out);
  }

  public void write(int cthrows IOException {
    inbuf[i= c;
    i++;
    if (i == 3) {
      super.write(toBase64[(inbuf[00xFC>> 2]);
      super.write(toBase64[((inbuf[00x03<< 4)
          ((inbuf[10xF0>> 4)]);
      super.write(toBase64[((inbuf[10x0F<< 2)
          ((inbuf[20xC0>> 6)]);
      super.write(toBase64[inbuf[20x3F]);
      col += 4;
      i = 0;
      if (col >= 76) {
        super.write('\n');
        col = 0;
      }
    }
  }

  public void flush() throws IOException {
    if (i == 1) {
      super.write(toBase64[(inbuf[00xFC>> 2]);
      super.write(toBase64[(inbuf[00x03<< 4]);
      super.write('=');
      super.write('=');
    else if (i == 2) {
      super.write(toBase64[(inbuf[00xFC>> 2]);
      super.write(toBase64[((inbuf[00x03<< 4)
          ((inbuf[10xF0>> 4)]);
      super.write(toBase64[(inbuf[10x0F<< 2]);
      super.write('=');
    }
    i = 0;
  }

  private static char[] toBase64 = 'A''B''C''D''E''F''G''H',
      'I''J''K''L''M''N''O''P''Q''R''S''T''U',
      'V''W''X''Y''Z''a''b''c''d''e''f''g''h',
      'i''j''k''l''m''n''o''p''q''r''s''t''u',
      'v''w''x''y''z''0''1''2''3''4''5''6''7',
      '8''9''+''/' };

  private int col = 0;

  private int i = 0;

  private int[] inbuf = new int[3];
}

class Base64InputStream extends FilterInputStream {
  public Base64InputStream(InputStream in) {
    super(in);
  }

  public int read(byte[] b, int off, int lenthrows IOException {
    if (len > b.length - off)
      len = b.length - off;
    for (int i = 0; i < len; i++) {
      int ch = read();
      if (ch == -1)
        return i;
      b[i + off(bytech;
    }
    return len;

  }

  public int read(byte[] bthrows IOException {
    return read(b, 0, b.length);
  }

  public int read() throws IOException {
    int r;
    if (i == 0) { // skip whitespace
      do {
        ch[0super.read();
        if (ch[0== -1)
          return -1;
      while (Character.isWhitespace((charch[0]));
      ch[1super.read();
      if (ch[1== -1)
        return -1;
      i++;
      r = (fromBase64[ch[0]] << 2(fromBase64[ch[1]] >> 4);
    else if (i == 1) {
      ch[2super.read();
      if (ch[2== '=' || ch[2== -1)
        return -1;
      i++;
      r = ((fromBase64[ch[1]] 0x0F<< 4(fromBase64[ch[2]] >> 2);
    else {
      ch[3super.read();
      if (ch[3== '=' || ch[3== -1)
        return -1;
      i = 0;
      r = ((fromBase64[ch[2]] 0x03<< 6| fromBase64[ch[3]];
    }
    return r;
  }

  private static int[] fromBase64 = -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -162,
      -1, -1, -16352535455565758596061, -1, -1, -1,
      -1, -1, -1, -101234567891011121314,
      1516171819202122232425, -1, -1, -1, -1, -1, -1,
      2627282930313233343536373839404142,
      434445464748495051, -1, -1, -1, -1, -};

  int i = 0;

  int[] ch = new int[4];
}

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