Copies a Transferable object to the system clipboard - Java Native OS

Java examples for Native OS:Clipboard

Description

Copies a Transferable object to the system clipboard

Demo Code


//package com.java2s;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.Transferable;

public class Main {
    /**/*from w ww. j a  va2 s .  com*/
     * The global Clipboard object that we use for all of
     * our calls -- it's static so it only has to get created
     * once, and can then be reused
     */
    private static Clipboard clipboard = null;

    /**
     * Copies a Transferable object to the system clipboard
     *
     * @param contents    the item to send to the clipboard, 
     *                    which must be an object of a class
     *                    that implements java.awt.datatransfer.Transferable
     */
    public static void copyTransferableObject(Transferable contents) {
        getClipboard();
        clipboard.setContents(contents, null);
    }

    /**
     * The private getClipboard method attempts to populate the
     * local clipboard variable with the system clipboard, if the
     * variable is currently null (if it's already been assigned
     * as the system clipboard, there's no need to assign it again).
     * The trick here is to get the system clipboard reference in
     * a daemon thread, so the AWT threads created by the call to
     * Toolkit.getDefaultToolkit() can be killed without the need
     * to call System.exit().
     */
    private static void getClipboard() {
        // this is our simple thread that grabs the clipboard
        Thread clipThread = new Thread() {
            public void run() {
                clipboard = Toolkit.getDefaultToolkit()
                        .getSystemClipboard();
            }
        };

        // start the thread as a daemon thread and wait for it to die
        if (clipboard == null) {
            try {
                clipThread.setDaemon(true);
                clipThread.start();
                clipThread.join();
            } catch (Exception e) {
            }
        }
    }
}

Related Tutorials