The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.awt.datatransfer  [3 examples]

e637. Getting and Setting Text on the System Clipboard

This examples defines methods for getting and setting text on the system clipboard.
    // If a string is on the system clipboard, this method returns it;
    // otherwise it returns null.
    public static String getClipboard() {
        Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    
        try {
            if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                String text = (String)t.getTransferData(DataFlavor.stringFlavor);
                return text;
            }
        } catch (UnsupportedFlavorException e) {
        } catch (IOException e) {
        }
        return null;
    }
    
    // This method writes a string to the system clipboard.
    // otherwise it returns null.
    public static void setClipboard(String str) {
        StringSelection ss = new StringSelection(str);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
    }

 Related Examples
e638. Getting and Setting an Image on the System Clipboard
e639. Determining When an Item Is No Longer on the System Clipboard


© 2002 Addison-Wesley.