java操作系统剪切板Clipboard及自定义剪切板

系统剪切板:

系统剪切板一般支持String文本类型和Image图像类型:

String文本类型

插入:

Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();//获取系统剪切板
	String str = "哈哈";//设置字符串
	StringSelection selection = new StringSelection(str);//构建String数据类型
	clipboard.setContents(selection, selection);//添加文本到系统剪切板

  获取:

Transferable content = clipboard.getContents(null);//从系统剪切板中获取数据
if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) {//判断是否为文本类型
	String text = (String) content.getTransferData(DataFlavor.stringFlavor);//从数据中获取文本值
	if (text == null) {
	    return;
	}
    System.out.println(text);

}

 

自定义剪切板:

首先需要写一个数据类:

public class TestSelection implements Transferable, ClipboardOwner {
    public static final DataFlavor rangeFlavor = new DataFlavor(RangeDataModel.class, "Report Range");//class为自定义的java类 字串随便
   private static final DataFlavor[] flavors = { rangeFlavor };
    private Object data;
    public TestSelection(Object data) {
		this.data = data;
	}
    
    @Override
	public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
		if (flavor.equals(flavors[RANGE])) {
			return data;
		} else {
			throw new UnsupportedFlavorException(flavor);
		}
	}

	@Override
	public DataFlavor[] getTransferDataFlavors() {
		return (DataFlavor[]) flavors.clone();
	}

	@Override
	public boolean isDataFlavorSupported(DataFlavor flavor) {
		for (int i = 0; i < flavors.length; i++) {
			if (flavor.equals(flavors[i])) {
				return true;
			}
		}
		return false;
	}

	@Override
	public void lostOwnership(Clipboard clipboard, Transferable contents) {
		// TODO Auto-generated method stub

	}


}

 然后就是设置值:

Clipboard clipboard = new Clipboard("clipboardName");//创建自定义剪切板对象

ReportSelection content = new ReportSelection(data);//构建数据对象 data为数据类型java类的对象
	clipboard.setContents(content, null);

 

获取值:

Transferable content = clipboard.getContents(null);//注意 自定义剪切板必须给null参数
if (content.isDataFlavorSupported(ReportSelection.rangeFlavor)) {
    RangeDataModel data = (RangeDataModel) content.getTransferData(ReportSelection.rangeFlavor);
    System.out.println(data);

}

 

 

你可能感兴趣的:(JAVA相关)