Method to paste a String from the Clip Board. - Java Native OS

Java examples for Native OS:Clipboard

Description

Method to paste a String from the Clip Board.

Demo Code


//package com.java2s;
import java.awt.Toolkit;
import java.io.IOException;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;

import java.awt.datatransfer.UnsupportedFlavorException;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(pasteString());
    }/* w w w . j  a  v a  2 s.c o m*/

    private static Clipboard clipboard = null;

    /**
     * Method to paste a String from the Clip Board.
     * created : Nov 20, 2006 8:59:48 PM
     * @return String
     */
    public static String pasteString() {
        String data = "";
        try {
            data = (String) pasteObject(DataFlavor.stringFlavor);
        } catch (Exception e) {
            System.err.println("Error getting String from clipboard: " + e);
        }

        return data;
    }

    /**
     * Method to paste an Object from the Clip Board.
     * created : Nov 20, 2006 8:59:54 PM
     * @return Object
     * @param DataFlavor flavor   : 
     *                        
     * @throws UnsupportedFlavorException
     * @throws IOException
     */
    private static Object pasteObject(DataFlavor flavor)
            throws UnsupportedFlavorException, IOException {
        Object obj = null;
        getClipboard();

        Transferable content = clipboard.getContents(null);
        if (content != null)
            obj = content.getTransferData(flavor);

        return obj;
    }

    /**
     * Method to get the Clip Board contents, it initializes the
     * ClipBoard object. It starts a sub thread to copy the contents.
     * created : Nov 20, 2006 8:55:21 PM
     */
    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) {
                e.printStackTrace();
            }
        }
    }
}

Related Tutorials