码迷,mamicode.com
首页 > 其他好文 > 详细

e638. 向剪切板获取和粘贴图像

时间:2018-09-02 23:53:49      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:nsf   his   null   OLE   order   sda   oid   ble   sys   

 // If an image is on the system clipboard, this method returns it;
    // otherwise it returns null.
    public static Image getClipboard() {
        Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    
        try {
            if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                Image text = (Image)t.getTransferData(DataFlavor.imageFlavor);
                return text;
            }
        } catch (UnsupportedFlavorException e) {
        } catch (IOException e) {
        }
        return null;
    }

Setting an image on the system clipboard requires a custom Transferable object to hold the image while on the clipboard.

    // This method writes a image to the system clipboard.
    // otherwise it returns null.
    public static void setClipboard(Image image) {
        ImageSelection imgSel = new ImageSelection(image);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel, null);
    }
    
    // This class is used to hold an image while on the clipboard.
    public static class ImageSelection implements Transferable {
        private Image image;
    
        public ImageSelection(Image image) {
            this.image = image;
        }
    
        // Returns supported flavors
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{DataFlavor.imageFlavor};
        }
    
        // Returns true if flavor is supported
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return DataFlavor.imageFlavor.equals(flavor);
        }
    
        // Returns image
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            if (!DataFlavor.imageFlavor.equals(flavor)) {
                throw new UnsupportedFlavorException(flavor);
            }
            return image;
        }
    }

 

Related Examples

e638. 向剪切板获取和粘贴图像

标签:nsf   his   null   OLE   order   sda   oid   ble   sys   

原文地址:https://www.cnblogs.com/borter/p/9575342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!