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

io.github.duoduobabi.javafx.util.ClipBoardUtils Maven / Gradle / Ivy

The newest version!
package io.github.duoduobabi.javafx.util;

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.image.BufferedImage;

/**
 * 粘贴板工具类
 *
 * @author cuiyang
 */
public class ClipBoardUtils {

    /**
     * 从剪切板获得文字。
     */
    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 ignore) {
                }
            }
        }
        return ret;
    }

    /**
     * 将字符串复制到剪切板。
     */
    public static void setSysClipboardText(String text) {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable tText = new StringSelection(text);
        clip.setContents(tText, null);
    }

    /**
     * 从剪切板获得图片。
     */
    public static BufferedImage getSysClipboardImg() {
        BufferedImage ret = null;
        Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 获取剪切板中的内容
        Transferable clipTf = sysClip.getContents(null);

        if (clipTf != null) {
            // 检查内容是否是文本类型
            if (clipTf.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                try {
                    ret = ImageUtils.toBufferedImage((Image) clipTf.getTransferData(DataFlavor.imageFlavor));
                } catch (Exception ignore) {
                }
            }
        }
        return ret;
    }

    /**
     * 将图片复制到剪切板。
     */
    public static void setSysClipboardImg(Image image) {
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable trans = new Transferable() {
            @Override
            public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
                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);
            }
        };

        clip.setContents(trans, null);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy