1 package snow.datatransfer; 2 3 import java.util.*; 4 import java.awt.datatransfer.*; 5 import java.awt.Toolkit ; 6 7 9 public final class ClipboardUtils implements FlavorListener 10 { 11 Vector<String > history = new Vector<String >(); 12 13 private static ClipboardUtils clipboardUtils; 15 private ClipboardUtils() 16 { 17 Toolkit.getDefaultToolkit().getSystemClipboard().addFlavorListener(this); 18 19 } 21 public synchronized static ClipboardUtils getInstance() 22 { 23 if(clipboardUtils==null) clipboardUtils = new ClipboardUtils(); 24 return clipboardUtils; 25 } 26 27 public List<String > getHistory() { return this.history; } 28 public void clearHistory() { history.clear(); } 29 private void addToHistory(String txt) 30 { 31 if(history.contains(txt)) return; 32 { 33 history.add(0, txt); 34 if(history.size()>20) 35 { 36 history.setSize(20); 37 } 38 } 39 } 40 41 45 public void flavorsChanged(FlavorEvent _fe) 46 { 47 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); 48 Transferable content = null; 49 50 for(int ti=0; ti<2; ti++) { 52 try 53 { 54 content = clipboard.getContents(null); 55 } 56 catch(IllegalStateException e) 57 { 58 try{ Thread.sleep(100); } catch(Exception exi) {} 63 } 64 } 65 66 if(content.isDataFlavorSupported(DataFlavor.stringFlavor)) 67 { 68 try 69 { 70 String cont = (String ) content.getTransferData(DataFlavor.stringFlavor); 71 addToHistory(cont); 72 return; 74 } 75 catch(Exception e) 76 { 77 e.printStackTrace(); 78 } 79 } 80 } 81 82 84 public static void copyToClipboard(String txt) 85 { 86 if(txt==null) return; 87 Toolkit.getDefaultToolkit().getSystemClipboard().setContents( new StringSelection(txt), null); 90 91 } 93 94 public static String getClipboardStringContent() 95 { 96 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); 97 Transferable content = clipboard.getContents(null); 98 if(content.isDataFlavorSupported(DataFlavor.stringFlavor)) 99 { 100 try 101 { 102 return ""+ content.getTransferData(DataFlavor.stringFlavor); 103 } 104 catch(Exception e) 105 { 106 return "error: "+e.getMessage(); 107 } 108 } 109 else 110 { 111 System.out.println("nothing to paste !"); 112 return ""; 113 } 114 115 } 116 117 118 146 147 public static void main(String [] arguments) 148 { 149 copyToClipboard( "Hello323"); 150 } 151 152 } | Popular Tags |