可以直接使用,在操作剪贴板中的图片时,确保剪贴板中存在,否则会抛异常
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
/**
* 在其中定义了对系统剪贴板的操作方法
* @author Administrator
*
*/
public class SystemClipboradUtil {
private static Clipboard sysClip = Toolkit.getDefaultToolkit()
.getSystemClipboard();
/**
* 从剪贴板中获得文本
* @return 获得的文本
* @throws IOException
* @throws UnsupportedFlavorException
*/
public static String getTextFromClipborad() throws UnsupportedFlavorException, IOException
{
String str=null;
if(sysClip.isDataFlavorAvailable(DataFlavor.stringFlavor))
{
str=(String) sysClip.getData(DataFlavor.stringFlavor);
}
return str;
}
/**
* 向剪贴板中写文本
*/
public static void setClipboradText(String text)
{
Transferable trans=new StringSelection(text);
sysClip.setContents(trans, null);
}
/**
* 从剪贴板中获得图像
* @return 获得的图像
* @throws IOException
* @throws UnsupportedFlavorException
*/
public static Image getImageFromClipborad() throws UnsupportedFlavorException, IOException
{
Image image=null;
if(sysClip.isDataFlavorAvailable(DataFlavor.imageFlavor))
{
image=(Image)sysClip.getData(DataFlavor.imageFlavor);
}
return image;
}
/**
* 向剪贴板中写图像
*/
public static void setClipboradImage(Image image)
{
Transferable trans=new ImageSelection(image);
sysClip.setContents(trans, null);
}
public static void main(String[] args) throws Exception {
Toolkit.getDefaultToolkit().getSystemClipboard().addFlavorListener(new FlavorListener() {
@Override
public void flavorsChanged(FlavorEvent e) {
System.out.println("changed!!! " + e.getSource() + " " + e.toString());
}
});
Thread.sleep(100000L);
}
}
/**
* 支持Image传输的transferable
* @author Administrator
*
*/
class ImageSelection implements Transferable,ClipboardOwner{
private Image image;
public ImageSelection(Image image)
{
this.image=image;
}
@Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if(isDataFlavorSupported(flavor))
return image;
throw new UnsupportedFlavorException(flavor);
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] {DataFlavor.imageFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor);
}
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
}
}