Java - Allgemein

Clipboard/Zwischenablage

java.awt.datatransfer.Clipboard
Das folgende Beispiel zeigt wie der Zugriff auf die Zwischenablage mit Java erfolgt:

package com.sowas.javawiki.clipboard;
 
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
 
public class ClipboardDemo implements ClipboardOwner {
 
    Clipboard clipboard = null;
 
    public static void main(String args[]) {
        ClipboardDemo clipboardDemo = new ClipboardDemo();
        String strValue = "Mein Text";
        System.out.println("Writing to Clipboard: \"" + strValue + "\"");  // "Mein Text"
        clipboardDemo.setToClipboard(strValue);
        System.out.println("Reading from Clipboard: \"" 
                           + clipboardDemo.getFromClipboard(DataFlavor.stringFlavor) + "\"");  // "Mein Text"
    }
 
    public ClipboardDemo() {
        clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    }
 
    public String getFromClipboard(DataFlavor flavor) {
        String str = null;
        Transferable contents = clipboard.getContents(this);
        if (contents == null) 
            return str;
 
        if (contents.isDataFlavorSupported(flavor)) {
            try {
                str = (String) contents.getTransferData(flavor);
            } catch (UnsupportedFlavorException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
 
        return (str.length() == 0 ? null : str);
    }
 
    public void setToClipboard(String str) {
        StringSelection strSel = new StringSelection(str);
        clipboard.setContents(strSel, this);
    }
 
    @Override
    public void lostOwnership(Clipboard clipboard, Transferable contents) {
    }
}

Eigene Werkzeuge
Werkzeuge

gratis Counter by GOWEB
seit 9.10.2007