Java Tutorial/Development/Clipboard

Материал из Java эксперт
Версия от 15:30, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Clip Text

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;
import java.util.StringTokenizer;
public class MainClass {
  public static void main(String args[]) {
    // void copyToClipboard() {
    String toClipboard = "Hello from Java!";
    StringSelection ss = new StringSelection(toClipboard);
    Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
    clip.setContents(ss, ss);
    // Paste
    clip = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable contents = clip.getContents(new MainClass().getClass());
    if (contents == null)
      System.out.println("The clipboard is empty.");
    else {
      if (contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        try {
          String data = (String) contents.getTransferData(DataFlavor.stringFlavor);
          if (data == null)
            System.out.println("null");
          else {
            StringTokenizer st = new StringTokenizer(data, "\n");
            while (st.hasMoreElements())
              System.out.println(st.nextToken());
          }
        } catch (IOException ex) {
          System.out.println("IOException");
        } catch (UnsupportedFlavorException ex) {
          System.out.println("UnsupportedFlavorException");
        }
      } else
        System.out.println("Wrong flavor.");
    }
  }
}





Copying data to system clipboard

import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
public class Main {
  public static void main(String[] argv) throws Exception {
  }
  // This method writes a string to the system clipboard.
  public static void copyToSystemClipboard(String str) {
    StringSelection ss = new StringSelection(str);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
  }
}





Determining When an Item Is No Longer on the System Clipboard

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
public class Main {
  public static void main(String[] argv) throws Exception {
    ClipboardOwner owner = new MyClipboardOwner();
    StringSelection ss = new StringSelection("A String");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, owner);
  }
}
class MyClipboardOwner implements ClipboardOwner {
  public void lostOwnership(Clipboard clipboard, Transferable contents) {
    System.out.println("lost");
  }
}





Get string value from clipboard

import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
public class Main {
  public static void main(String[] argv) {
    System.out.println(getClipboard());
  }
  public static String getClipboard() {
    Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    try {
      if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
        String text = (String) t.getTransferData(DataFlavor.stringFlavor);
        return text.trim();
      }
    } catch (Exception e) {
    }
    return "";
  }
}





Getting and Setting an Image on the System Clipboard

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
public class Main {
  public static void main(String[] argv) throws Exception {
    Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
      Image img = (Image) t.getTransferData(DataFlavor.imageFlavor);
    }
  }
}





Getting data from the computer clipboard

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
public class Main {
  public static void main(String[] args) throws Exception {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable tran = clipboard.getContents(null);
    if (tran != null && tran.isDataFlavorSupported(DataFlavor.stringFlavor)) {
      String clipboardContent = (String) tran.getTransferData(DataFlavor.stringFlavor);
      System.out.println(clipboardContent);
    }
  }
}





implements ClipboardOwner

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
public class Main {
  public static void main(String[] argv) throws Exception {
    ClipboardOwner owner = new MyClipboardOwner();
    StringSelection ss = new StringSelection("A String");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, owner);
  }
}
class MyClipboardOwner implements ClipboardOwner {
  public void lostOwnership(Clipboard clipboard, Transferable contents) {
    System.out.println("lost");
  }
}





Placing text on the computer clipboard

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
public class Main {
  public static void main(String[] args) {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(new StringSelection("string"), null);
  }
}





Read Clipboard

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import javax.swing.JFrame;
public class MainClass extends JFrame {
  public static void main(String args[]) {
    Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
    System.out.println("Object Name: " + clip.getName());
    Transferable contents = clip.getContents(new MainClass().getClass());
    if (contents == null)
      System.out.println("\n\nThe clipboard is empty.");
    else {
      DataFlavor flavors[] = contents.getTransferDataFlavors();
      for (int i = 0; i < flavors.length; ++i) {
        System.out.println("\n\n Name: " + flavors[i].getHumanPresentableName());
        System.out.println("\n MIME Type: " + flavors[i].getMimeType());
        Class cl = flavors[i].getRepresentationClass();
        if (cl == null)
          System.out.println("null");
        else
          System.out.println(cl.getName());
      }
    }
  }
}





Setting an image on the clipboard with a custom Transferable object to hold the image

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import javax.swing.ImageIcon;
public class Main {
  public static void main(String[] argv) throws Exception {
    ImageSelection imgSel = new ImageSelection(new ImageIcon("a.png").getImage());
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel, null);
  }
}
class ImageSelection implements Transferable {
  private Image image;
  public ImageSelection(Image image) {
    this.image = image;
  }
  public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[] { DataFlavor.imageFlavor };
  }
  public boolean isDataFlavorSupported(DataFlavor flavor) {
    return DataFlavor.imageFlavor.equals(flavor);
  }
  public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (!DataFlavor.imageFlavor.equals(flavor)) {
      throw new UnsupportedFlavorException(flavor);
    }
    return image;
  }
}





Using the clipboard

// This example is from the book _Java AWT Reference_ by John Zukowski.
// Written by John Zukowski.  Copyright (c) 1997 O"Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or
import java.awt.Button;
import java.awt.Event;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
public class ClipMe extends Frame {
  TextField tf;
  TextArea ta;
  Button copy, paste;
  Clipboard clipboard = null;
  ClipMe() {
    super("Clipping Example");
    add(tf = new TextField("Welcome"), "North");
    add(ta = new TextArea(), "Center");
    ta.setEditable(false);
    Panel p = new Panel();
    p.add(copy = new Button("Copy"));
    p.add(paste = new Button("Paste"));
    add(p, "South");
    setSize(250, 250);
  }
  public static void main(String args[]) {
    new ClipMe().show();
  }
  public boolean handleEvent(Event e) {
    if (e.id == Event.WINDOW_DESTROY) {
      System.exit(0);
      return true; // never gets here
    }
    return super.handleEvent(e);
  }
  public boolean action(Event e, Object o) {
    if (clipboard == null)
      clipboard = getToolkit().getSystemClipboard();
    if ((e.target == tf) || (e.target == copy)) {
      StringSelection data;
      data = new StringSelection(tf.getText());
      clipboard.setContents(data, data);
    } else if (e.target == paste) {
      Transferable clipData = clipboard.getContents(this);
      String s;
      try {
        s = (String) (clipData.getTransferData(DataFlavor.stringFlavor));
      } catch (Exception ee) {
        s = ee.toString();
      }
      ta.setText(s);
    }
    return true;
  }
}





Write a string to the system clipboard

import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
public class Main {
  public static void main(String[] argv) throws Exception {
    StringSelection ss = new StringSelection("str");
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
  }
}