Java by API/java.awt.datatransfer/Transferable

Материал из Java эксперт
Перейти к: навигация, поиск

implements Transferable

 
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import javax.swing.AbstractButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.TransferHandler;
public class MainClass {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Drag Image");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Icon icon = new ImageIcon("image.jpg");
    JLabel label = new JLabel(icon);
    label.setTransferHandler(new ImageSelection());
    MouseListener listener = new MouseAdapter() {
      public void mousePressed(MouseEvent me) {
        JComponent comp = (JComponent) me.getSource();
        TransferHandler handler = comp.getTransferHandler();
        handler.exportAsDrag(comp, me, TransferHandler.COPY);
      }
    };
    label.addMouseListener(listener);
    frame.add(new JScrollPane(label), BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}
class ImageSelection extends TransferHandler implements Transferable {
  private static final DataFlavor flavors[] = { DataFlavor.imageFlavor };
  private Image image;
  public int getSourceActions(JComponent c) {
    return TransferHandler.COPY;
  }
  public boolean canImport(JComponent comp, DataFlavor flavor[]) {
    if (!(comp instanceof JLabel) && !(comp instanceof AbstractButton)) {
      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) {
    image = null;
    if (comp instanceof JLabel) {
      JLabel label = (JLabel) comp;
      Icon icon = label.getIcon();
      if (icon instanceof ImageIcon) {
        image = ((ImageIcon) icon).getImage();
        return this;
      }
    } else if (comp instanceof AbstractButton) {
      AbstractButton button = (AbstractButton) comp;
      Icon icon = button.getIcon();
      if (icon instanceof ImageIcon) {
        image = ((ImageIcon) icon).getImage();
        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) {
        }
      }
    } else if (comp instanceof AbstractButton) {
      AbstractButton button = (AbstractButton) comp;
      if (t.isDataFlavorSupported(flavors[0])) {
        try {
          image = (Image) t.getTransferData(flavors[0]);
          ImageIcon icon = new ImageIcon(image);
          button.setIcon(icon);
          return true;
        } catch (UnsupportedFlavorException ignored) {
        } catch (IOException ignored) {
        }
      }
    }
    return false;
  }
  public Object getTransferData(DataFlavor flavor) {
    if (isDataFlavorSupported(flavor)) {
      return image;
    }
    return null;
  }
  public DataFlavor[] getTransferDataFlavors() {
    return flavors;
  }
  public boolean isDataFlavorSupported(DataFlavor flavor) {
    return flavors[0].equals(flavor);
  }
}





Transferable: getTransferData(DataFlavor flavor)

 
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
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.DragSourceContext;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
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.awt.dnd.InvalidDnDOperationException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MainClass extends JFrame implements ActionListener, DropTargetListener {
  DragLabel source = new DragLabel("Drag and drop me to the following JButton", JLabel.CENTER);
  JButton target = new JButton();
  MainClass(String title) {
    super(title);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    source.setForeground(Color.red);
    getContentPane().add(source, BorderLayout.NORTH);
    target.addActionListener(this);
    getContentPane().add(target, BorderLayout.SOUTH);
    new DropTarget(target, DnDConstants.ACTION_COPY_OR_MOVE, this);
    setSize(205, 100);
    setVisible(true);
  }
  public void actionPerformed(ActionEvent e) {
    JButton b = (JButton) e.getSource();
    b.setText("");
    source.setText("Drag and drop me to the following JButton");
  }
  public void dragEnter(DropTargetDragEvent e) {
    System.out.println("Entering drop target #1");
  }
  public void dragExit(DropTargetEvent e) {
    System.out.println("Exiting drop target #1");
  }
  public void dragOver(DropTargetDragEvent e) {
    System.out.println("Dragging over drop target #1");
  }
  public void drop(DropTargetDropEvent e) {
    System.out.println("Dropping");
    try {
      Transferable t = e.getTransferable();
      if (e.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        e.acceptDrop(e.getDropAction());
        String s;
        s = (String) t.getTransferData(DataFlavor.stringFlavor);
        target.setText(s);
        e.dropComplete(true);
      } else
        e.rejectDrop();
    } catch (java.io.IOException e2) {
    } catch (UnsupportedFlavorException e2) {
    }
  }
  public void dropActionChanged(DropTargetDragEvent e) {
    System.out.println("Drop action changed #1");
  }
  public static void main(String[] args) {
    new MainClass("Drag and Drop Demo");
  }
}
class DragLabel extends JLabel implements DragGestureListener, DragSourceListener {
  private DragSource ds = DragSource.getDefaultDragSource();
  public DragLabel(String s, int alignment) {
    super(s, alignment);
    int action = DnDConstants.ACTION_COPY_OR_MOVE;
    ds.createDefaultDragGestureRecognizer(this, action, this);
  }
  public void dragGestureRecognized(DragGestureEvent e) {
    try {
      Transferable t = new StringSelection(getText());
      e.startDrag(DragSource.DefaultCopyNoDrop, t, this);
    } catch (InvalidDnDOperationException e2) {
      System.out.println(e2);
    }
  }
  public void dragDropEnd(DragSourceDropEvent e) {
    System.out.println("Drag and drop end");
    if (e.getDropSuccess() == false) {
      System.out.println("unsuccessful");
      return;
    }
    int action = e.getDropAction();
    if ((action & DnDConstants.ACTION_MOVE) != 0)
      setText("");
  }
  public void dragEnter(DragSourceDragEvent e) {
    System.out.println("Entering drop target #2");
    DragSourceContext ctx = e.getDragSourceContext();
    int action = e.getDropAction();
    if ((action & DnDConstants.ACTION_COPY) != 0)
      ctx.setCursor(DragSource.DefaultCopyDrop);
    else
      ctx.setCursor(DragSource.DefaultCopyNoDrop);
  }
  public void dragExit(DragSourceEvent e) {
    System.out.println("Exiting drop target #2");
  }
  public void dragOver(DragSourceDragEvent e) {
    System.out.println("Dragging over drop target #2");
  }
  public void dropActionChanged(DragSourceDragEvent e) {
    System.out.println("Drop action changed #2");
  }
}





Transferable: getTransferDataFlavors()

 
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.TransferHandler;
public class MainClass extends JFrame {
  public MainClass() {
    super("Drop Target");
    JComponent cp = (JComponent) getContentPane();
    cp.setTransferHandler(new MyFileTransferHandler()); // see below
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(150, 150);
  }
  public static void main(String[] args) {
    new MainClass().setVisible(true);
  }
}
class MyFileTransferHandler extends TransferHandler {
  public boolean canImport(JComponent com, DataFlavor[] dataFlavors) {
    for (int i = 0; i < dataFlavors.length; i++) {
      DataFlavor flavor = dataFlavors[i];
      if (flavor.equals(DataFlavor.javaFileListFlavor)) {
        System.out.println("canImport: JavaFileList FLAVOR: " + flavor);
        return true;
      }
      if (flavor.equals(DataFlavor.stringFlavor)) {
        System.out.println("canImport: String FLAVOR: " + flavor);
        return true;
      }
      System.err.println("canImport: Rejected Flavor: " + flavor);
    }
    return false;
  }
  public boolean importData(JComponent comp, Transferable t) {
    DataFlavor[] flavors = t.getTransferDataFlavors();
    System.out.println("Trying to import:" + t);
    for (int i = 0; i < flavors.length; i++) {
      DataFlavor flavor = flavors[i];
      try {
        if (flavor.equals(DataFlavor.javaFileListFlavor)) {
          System.out.println("importData: FileListFlavor");
          List l = (List) t.getTransferData(DataFlavor.javaFileListFlavor);
          Iterator iter = l.iterator();
          while (iter.hasNext()) {
            File file = (File) iter.next();
            System.out.println("GOT FILE: " + file.getCanonicalPath());
          }
          return true;
        } else if (flavor.equals(DataFlavor.stringFlavor)) {
          System.out.println("importData: String Flavor");
          String fileOrURL = (String) t.getTransferData(flavor);
          System.out.println("GOT STRING: " + fileOrURL);
          try {
            URL url = new URL(fileOrURL);
            System.out.println("Valid URL: " + url.toString());
            return true;
          } catch (MalformedURLException ex) {
            System.err.println("Not a valid URL");
            return false;
          }
        } else {
          System.out.println("importData rejected: " + flavor);
        }
      } catch (IOException ex) {
        System.err.println("IOError getting data: " + ex);
      } catch (UnsupportedFlavorException e) {
        System.err.println("Unsupported Flavor: " + e);
      }
    }
    return false;
  }
}





Transferable: isDataFlavorSupported(DataFlavor flavor)

      
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
public class Main {
  public static void main(String args[]) {
    String toClipboard = "Hello from Java!";
    StringSelection ss = new StringSelection(toClipboard);
    Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
    clip.setContents(ss, ss);
    clip = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable contents = clip.getContents(new Main().getClass());
    if (contents == null) {
      System.out.println("The clipboard is empty.");
      return;
    }
    if (contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
      try {
        String data = (String) contents.getTransferData(DataFlavor.stringFlavor);
        System.out.println(data);
      } catch (IOException ex) {
        System.out.println("IOException");
      } catch (UnsupportedFlavorException ex) {
        System.out.println("UnsupportedFlavorException");
      }
    } else{
      System.out.println("Wrong flavor.");
    }
  }
}