Sunday, February 17, 2008

Getting data from the computer clipboard

Getting data from the system clipboard is implemented nicely in Java through the Toolkit class which has a getSystemClipboard method.
Since there isn't necessarily text contents in the clipboard the getSystemClipboard returns an instance of the class Transferable.
With that instance we have to test if the content is text before we do any processing with it. To test the code, just copy some text from the browser or some other document and have the java program print it out.
package com.javadb.example;

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;

/**
 *
 * @author javadb.com
 */
public class Main {

    /**
     * Displays text from the clipboard
     */
    public void displayTextFromClipboard() {
        
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Clipboard clipboard = toolkit.getSystemClipboard();
        Transferable tran = null;
        
        try {
            
            //The parameter to getContents is not currently used so null should
            //be sent. If the clipboard is currently not available (for example 
            //it is used by another application) the method throws an
            //IllegalStateException.
            tran = clipboard.getContents(null);
            
        } catch (IllegalStateException ex) {
            System.out.println("The clipboard is unavailable.");
            return;
        }
        
        if (tran != null &&
                tran.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            
            try {
                
                String clipboardContent =
                        (String)tran.getTransferData(DataFlavor.stringFlavor);
                
                System.out.println(clipboardContent);
                
            } catch (UnsupportedFlavorException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().displayTextFromClipboard();
    }
    
}

 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory