All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.azbh111.utils.java.clipboard.ClipboardUtils Maven / Gradle / Ivy

The newest version!
package com.github.azbh111.utils.java.clipboard;

import java.awt.*;
import java.awt.datatransfer.*;
import java.io.IOException;

/**
 *
 * @author pyz
 * @date 2019/4/3 10:30 PM
 */
public class ClipboardUtils {
    //获取系统剪切板
    public static final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

    public static void setString(String str) {
        StringSelection selection = new StringSelection(str);
        clipboard.setContents(selection, null);
    }

    public static String getString() {
        Transferable content = clipboard.getContents(null);
        if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            try {
                return (String) content.getTransferData(DataFlavor.stringFlavor);
            } catch (IOException | UnsupportedFlavorException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    public static void setImage(Image image) {
        ImageSelection imgSel = new ImageSelection(image);
        clipboard.setContents(imgSel, null);
    }

    public static Image getImage() {
        Transferable t = clipboard.getContents(null);
        try {
            if (null != t && t.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                return (Image) t.getTransferData(DataFlavor.imageFlavor);
            }
        } catch (IOException | UnsupportedFlavorException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    public static class ImageSelection implements Transferable {
        private Image image;

        public ImageSelection(Image image) {
            this.image = image;
        }

        @Override
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{DataFlavor.imageFlavor};
        }

        @Override
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return DataFlavor.imageFlavor.equals(flavor);
        }

        @Override
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            if (!DataFlavor.imageFlavor.equals(flavor)) {
                throw new UnsupportedFlavorException(flavor);
            }
            return image;
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy