开发者

How can I use Java to place a jpg file into the clipboard, so that it can be pasted into any document as an image?

I often have to add my signature to a document. The document can be of different kinds. My signature is stored as an image in signature.jpg.

I would like to write 开发者_如何学JAVAa Java program that automatically places this image in the clipboard, so that I only have to paste it into the document.


You have to use me method: setContents from the Clipboard class.

Modified from: http://www.exampledepot.com/egs/java.awt.datatransfer/ToClipImg.html

import java.awt.*;
import java.awt.datatransfer.*;
public class LoadToClipboard {
    public static void main( String [] args ) {
        Toolkit tolkit = Toolkit.getDefaultToolkit();
        Clipboard clip = tolkit.getSystemClipboard();        
        clip.setContents( new ImageSelection( tolkit.getImage("StackOverflowLogo.png")) , null );
    }
}
class ImageSelection implements Transferable {
        private Image image;

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

        // Returns supported flavors
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{DataFlavor.imageFlavor};
        }

        // Returns true if flavor is supported
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return DataFlavor.imageFlavor.equals(flavor);
        }

        // Returns image
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
            if (!DataFlavor.imageFlavor.equals(flavor)) {
                throw new UnsupportedFlavorException(flavor);
            }
            return image;
        }
    }


Take a look at the java.awt.datatransfer.* classes. You'll essentially have to develop an implementation of the java.awt.datatransfer.Transferable interface that will transfer an image to the clipboard.

Edit: Found a couple of tutorials that might help:

  • Java Tip #61
  • Use Java to Interact with Your Clipboard (see page 6 of the tutorial)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜