Copy to clipboard

While working on the Baking Blogger’s special characters panel, I needed a way to copy the selected character to the clipboard. I used the following technique:
import java.awt.Toolkit;
import java.awt.datatransfer.*;

TextTransfer clipBoard = new TextTransfer();

Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, this);
clipBoard.setClipboardContents(button4.getText());

class TextTransfer implements ClipboardOwner {
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
}

public void setClipboardContents(String aString) {
StringSelection stringSelection = new StringSelection(aString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, this);
}
}



Start with writing a class that implements the ClipboardOwner interface. This enforces you to implement the method setClipaordContents(String string){}

Author: nurnachman

Software Developer, Love Cats.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.