paste From Clipboard - Java Native OS

Java examples for Native OS:Clipboard

Description

paste From Clipboard

Demo Code


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

import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

public class Main {
    public static void main(String[] argv) throws Exception {
        pasteFromClipboard();//from   ww  w  . j av a2 s  .c  o m
    }

    public static synchronized void pasteFromClipboard() {
        Clipboard clipboard = Toolkit.getDefaultToolkit()
                .getSystemClipboard();

        // get clipboard context
        Transferable data = clipboard.getContents(null);

        // is context string type

        boolean bIsText = ((data != null) && (data
                .isDataFlavorSupported(DataFlavor.stringFlavor)));

        // if yes, translate context to string type and write it

        if (bIsText) {

            try {
                String s = (String) data
                        .getTransferData(DataFlavor.stringFlavor);
                System.out.println(s);

            } catch (UnsupportedFlavorException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}

Related Tutorials