java 复制文本到剪贴板

来源:互联网 发布:php sha1 解密 编辑:程序博客网 时间:2024/05/21 20:29
在java awt中使用Clipboard类控制剪贴板,将文本复制到剪贴板很容易,如下代码实现:

package cn.outofmemory.example;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;

/**
*
* @author outofmemory.cn
*/
public class Main {

/**
* Places text on the clipboard
*/
public void placeTextOnClipboard() {

//Get the toolkit
Toolkit toolkit = Toolkit.getDefaultToolkit();

//Get the clipboard
Clipboard clipboard = toolkit.getSystemClipboard();

//The setContents method of the Clipboard instance takes a Transferable
//as first parameter. The StringSelection class implements the Transferable
//interface.
StringSelection stringSel = new StringSelection("text to be placed on the clipboard");

//We specify null as the clipboard owner
clipboard.setContents(stringSel, null);

}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().placeTextOnClipboard();
}

}
0 0