1 package com.clipboard.test; 2 3 import java.awt.Toolkit; 4 import java.awt.datatransfer.Clipboard; 5 import java.awt.datatransfer.DataFlavor; 6 import java.awt.datatransfer.StringSelection; 7 8 public class SimpleClipboard { 9 10 public static void main(String[] args) { 11 // 创建系统剪贴板 12 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); 13 14 // 创建本地剪贴板 15 // Clipboard clipboard = new Clipboard("cd"); 16 17 StringSelection contents = new StringSelection("this is content"); 18 // 通过将文本封装成StringSelection对象,并调用setContents方法,放入剪贴板中 19 clipboard.setContents(contents, null); 20 21 // 下面是获取剪贴板中的内容 22 if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) { 23 try { 24 String content = (String) clipboard.getData(DataFlavor.stringFlavor); 25 System.out.println(content); 26 } catch (Exception e) { 27 e.printStackTrace(); 28 } 29 30 } 31 32 } 33 34 }
时间: 2024-10-19 05:24:44