本文主要是介绍Java 访问(复制,粘贴)剪切板,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
以下共有4个函数分别是:1.从剪切板获得文字。
2.将字符串复制到剪切板。
3.从剪切板获得图片。
4.复制图片到剪切板。
/*** 从剪切板获得文字。*/public static String getSysClipboardText() {String ret = "";Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();// 获取剪切板中的内容Transferable clipTf = sysClip.getContents(null);if (clipTf != null) {// 检查内容是否是文本类型if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {try {ret = (String) clipTf.getTransferData(DataFlavor.stringFlavor);} catch (Exception e) {e.printStackTrace();}}}return ret;}/*** 将字符串复制到剪切板。*/public static void setSysClipboardText(String writeMe) {Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();Transferable tText = new StringSelection(writeMe);clip.setContents(tText, null);}/*** 从剪切板获得图片。*/public static Image getImageFromClipboard() throws Exception {Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();Transferable cc = sysc.getContents(null);if (cc == null)return null;else if (cc.isDataFlavorSupported(DataFlavor.imageFlavor))return (Image) cc.getTransferData(DataFlavor.imageFlavor);return null;}/*** 复制图片到剪切板。*/public static void setClipboardImage(final Image image) {Transferable trans = new Transferable() {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 (isDataFlavorSupported(flavor))return image;throw new UnsupportedFlavorException(flavor);}};Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,null);}
来源:http://blog.csdn.net/aminfo/article/details/7858109
这篇关于Java 访问(复制,粘贴)剪切板的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!