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;

 * @author
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
            tran = clipboard.getContents(null);
        } catch (IllegalStateException ex) {
            System.out.println("The clipboard is unavailable.");
        if (tran != null &&
                tran.isDataFlavorSupported(DataFlavor.stringFlavor)) {
            try {
                String clipboardContent =
            } catch (UnsupportedFlavorException ex) {
            } catch (IOException ex) {
     * @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 & Programming Blogs - BlogCatalog Blog Directory