Stanislav Zorjan - Stasha - Full Stack Software Engineer and Game Development Hobbyist - Prague


If you have need to copy text to clipboard and paste text from clipboard but you don't know how, here is a simple Class to help you. Just create new instance and use methods "copyTextToClipboard("some text")" and "copyTextFromClipboard()".

/***********************************************************************************************
* TEXTCLIPBOARD CLASS
*
* @author Stanislav Zorjan
* @copyright (c)Copyright 2007 - 2008 - Stanislav Zorjan newcomponents@neobee.net
*
* Text clipboard class copies text from and to clipboard
*/
/***********************************************************************************************/
/*change package name to Your package name*/
package draggwindow;
import java.awt.datatransfer.Transferable;
import java.io.IOException;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
public class TextClipboard implements ClipboardOwner {
    private SecurityManager securityManager = System.getSecurityManager();   
    private Toolkit toolkit = Toolkit.getDefaultToolkit();
    private StringSelection stringSelection;
    private Clipboard clipboard;
    private String result;
    private Transferable contents;
	
	
    public void copyTextToClipboard(String text) {
		
        if (this.securityManager != null) {
            try {
                this.securityManager.checkSystemClipboardAccess();
            } catch (Exception e) {
				e.printStackTrace();
			}
        }
        
        this.stringSelection = new StringSelection(text);
        this.clipboard = toolkit.getSystemClipboard();
        this.clipboard.setContents(stringSelection, this);
    }
    
	
    public String copyTextFromClipboard() {
        this.result = "";
        this.clipboard = this.toolkit.getSystemClipboard();
        
        this.contents = this.clipboard.getContents(null);
		
        boolean hasTransferableText =(this.contents != null) && this.contents.isDataFlavorSupported(DataFlavor.stringFlavor);
		
        if ( hasTransferableText ) {
            try {
                this.result = (String)this.contents.getTransferData(DataFlavor.stringFlavor);
            } catch (UnsupportedFlavorException ex){
                System.out.println(ex);
                ex.printStackTrace();
            } catch (IOException ex) {
                System.out.println(ex);
                ex.printStackTrace();
            }
        }
        return result;
    }
	
    public void lostOwnership(Clipboard clip, Transferable tr) {
        System.out.println("Lost Clipboard Ownership?!?");
    } 
}