com.github.azbh111.utils.java.clipboard.ClipboardUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of utils-java Show documentation
Show all versions of utils-java Show documentation
com.github.azbh111:utils-java
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;
}
}
}