Created
March 30, 2024 13:37
-
-
Save mildsunrise/917934c4bfd5105ad6489b69ac9d58a2 to your computer and use it in GitHub Desktop.
copy a test image to the clipboard using Java AWT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.*; | |
import java.awt.datatransfer.*; | |
import java.awt.image.*; | |
import java.io.*; | |
public class Main { | |
public static void main(String[] arg) { | |
var flavorMap = (FlavorTable) SystemFlavorMap.getDefaultFlavorMap(); | |
System.out.println("formats for image flavor: "); | |
for (var format : flavorMap.getNativesForFlavor(DataFlavor.imageFlavor)) | |
System.out.println(" - " + format); | |
var clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); | |
var image = new BufferedImage(100, 100, BufferedImage.TYPE_3BYTE_BGR); | |
var contents = new TransferableImage(image); | |
var owner = new MyOwner(); | |
clipboard.setContents(contents, owner); | |
System.out.println("blank image copied to clipboard!"); | |
System.out.println("process will stay alive until something else is copied."); | |
owner.waitForLost(); | |
} | |
private static class MyOwner implements ClipboardOwner { | |
private boolean lost = false; | |
public synchronized void lostOwnership(Clipboard clip, Transferable trans) { | |
System.out.println("lost ownership."); | |
lost = true; | |
notifyAll(); | |
} | |
synchronized void waitForLost() { | |
try { | |
while (!lost) | |
wait(); | |
} catch (InterruptedException ex) { | |
throw new RuntimeException(ex); | |
} | |
} | |
} | |
private static class TransferableImage implements Transferable { | |
Image i; | |
public TransferableImage(Image i) { | |
this.i = i; | |
} | |
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException { | |
if (flavor.equals(DataFlavor.imageFlavor)) | |
return i; | |
throw new UnsupportedFlavorException(flavor); | |
} | |
public DataFlavor[] getTransferDataFlavors() { | |
return new DataFlavor[] { DataFlavor.imageFlavor }; | |
} | |
public boolean isDataFlavorSupported(DataFlavor flavor) { | |
return flavor.equals(DataFlavor.imageFlavor); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment