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

com.ideaaedi.commonds.quick.ClipboardUtil Maven / Gradle / Ivy

The newest version!
package com.ideaaedi.commonds.quick;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;

/**
 * 剪切板工具类
 *
 * @author JustryDeng 
 * @since 1.0.0
 */
public final class ClipboardUtil {
    
    private ClipboardUtil() {
        throw new UnsupportedOperationException();
    }
    
    /**
     * 粘贴
     *
     * @return 剪切板中的文本
     */
    public static String getClipboardString() {
        // 获取系统剪贴板
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 获取剪贴板中的内容
        Transferable trans = clipboard.getContents(null);
        if (trans != null) {
            // 只从剪切板获取文本
            if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                try {
                    return (String) trans.getTransferData(DataFlavor.stringFlavor);
                } catch (Exception e) {
                    // ignore
                }
            }
        }
        return null;
    }
    
    /**
     * 复制
     *
     * @param text
     *         要复制的文本
     */
    public static void setClipboardString(String text) {
        try {
            // 获取系统剪贴板
            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            // 封装文本内容
            Transferable trans = new StringSelection(text);
            // 把文本内容设置到系统剪贴板
            clipboard.setContents(trans, null);
        } catch (Exception e) {
            // ignore
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy