java 如何使用WINDOWS下的剪贴板?
我想把程序里面的1个String 自动复制到WINDOWS系统剪贴板底下 以后操作直接用ctrl+V就能按出来 怎么做?
------解决方案--------------------帮忙顶
------解决方案--------------------如果是JTextArea,JTextField等,用它的copy(),cut(),paste()方法,如果想复制Image或想玩转系统的剪切板,请用java.awt.datatransfer包.
------解决方案--------------------簡單的將String寫入到操作系統的剪貼板中,可以參考:
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
public class WriteString
{
public static void main(String[] args)
{
Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();
setClipboardString(sysc, "寫入剪貼板的String ");
}
protected static void setClipboardString(Clipboard clip, String writeMe) {
Transferable tText = new StringSelection(writeMe);
clip.setContents(tText, null);
}
}
由於拷貝String,jdk中已經有類StringSelection支持,如果要拷貝一個文件,或者目錄,則要參考此類,對其進行修改,類名:FileSelection.java (改的可能不是很成功,但能夠用)
內容為:
/* @(#)FileSelection.java 07/05/14
* @author me
* Copy file from FoxEDM,Paste to System(e.g:2000 or xp etc)
*/
package com.foxera.foxlink.ui;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.*;
import java.util.List;
import java.util.ArrayList;
/**
* A <code> Transferable </code> which implements the capability required
* to transfer a <code> String </code> .
*
* This <code> Transferable </code> properly supports
* <code> DataFlavor.javaFileListFlavor </code>
* and all equivalent flavors. Support for
* <code> DataFlavor.plainTextFlavor </code>
* and all equivalent flavors is <b> deprecated </b> . No other
* <code> DataFlavor </code> s are supported.
*
* @see java.awt.datatransfer.DataFlavor#javaFileListFlavor
* @see java.awt.datatransfer.DataFlavor#plainTextFlavor
*/
public class FileSelection implements Transferable, ClipboardOwner {
private static final int FILE= 0;
private static final int PLAIN_FILE = 1;
private static final DataFlavor[] flavors = {
DataFlavor.javaFileListFlavor,
DataFlavor.javaFileListFlavor
};
private List data;
/**
* Creates a <code> Transferable </code> capable of transferring
* the specified <code> String </code> .
*/
public FileSelection(List data) {
this.data = data;
}
/**
* Returns an array of flavors in which this <code> Transferable </code>
* can provide the data. <code> DataFlavor.javaFileListFlavor </code>
* is properly supported.
* Support for <code> DataFlavor.plainTextFlavor </code> is
* <b> deprecated </b> .
*
* @return an array of length two, whose elements are <code> DataFlavor.
* stringFlavor </code> and <code> DataFlavor.plainTextFlavor </code>
*/
public DataFlavor[] getTransferDataFlavors() {
// returning flavors itself would allow client code to modify
// our internal behavior
return (DataFlavor[])flavors.clone();