Sunday, March 15, 2009

Eczema Vs. Lupus Rash

How to access the system clipboard in Java Streaming

Per accedere alla clipboard è sufficiente invocare il metodo getSystemClipboard() della classe java.awt.Toolkit che restituisce l'istanza singleton della Clipboad del sistema:
 Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); 
Per recuperarne il contenuto si dovrà poi richiamare il metodo getContents di java.awt.datatransfer.Clipboard che restituisce un oggetto di tipo java.awt.datatransfer.Transferable .
Come argomento del metodo si può passare tranquillamente null in quanto si tratta di un argomento che attualmente non viene utilizzato.
 Transferable contents = clipboard.getContents(null); 
Una volta ottenuto questo riferimento basterà controllare che sia presente del contenuto testuale, tramite la chiamata contents.isDataFlavorSupported(DataFlavor.stringFlavor) , e quindi recuperarne il valore mediante il metodo getTransferData :
 if(contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) 
  String str = (String) contents.getTransferData (DataFlavor.stringFlavor)
The method could, however, raise the following exceptions, which should be properly managed:
java.io.IOException
java.awt.datatransfer.UnsupportedFlavorException

This long around to retrieve the contents of the clipboard is due to the fact that the clipboard content can reside other than plain text. In addition, different operating systems may handle different types of content, it is necessary to take all necessary precautions!

code soon to recover the text from the clipboard, however, could be the following:
 String str; 
try {
  str = (String)Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null).getTransferData(DataFlavor.stringFlavor)
}catch(Exception e){
  str = "";
}
Attenzione perché nel breve codice riportato non stiamo difatti gestendo adeguatamente le eccezioni ma semplicemente settando la nostra variabile String str con una stringa vuota se qualcosa va male (incluso l'eventuale NullPointerException se il content della Clipboard è null): tutto ciò non è proprio il massimo in termini di gestione delle eccezioni ma è certamente un codice faster and more powerful than any version with similar if and controls.

The advice is - as always - take a look at the Java API and in particular:
http://java.sun.com/.../api/java/awt/Toolkit.html # getSystemClipboard ()
http://java.sun.com/.../api/java/awt/datatransfer/Clipboard.html # getContents (...)
http://java.sun.com/ ... / api / java / awt / datatransfer / Transferable.html # getTransferData (..)

The argument is also closely related to drag and drop for which there is a tutorial of the Sun in this Address:
http://java.sun.com/docs/books/tutorial/uiswing/dnd/intro.html