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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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