This example shows how to get the text string from the clipboard in Java.
AWT Clipboard class method getContents used to get copied content or data.
Get Copied Data from Clipboard – Java AWT Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; public class Main { public void displayTextFromClipboard() { Toolkit toolkit = Toolkit.getDefaultToolkit(); Clipboard clipboard = toolkit.getSystemClipboard(); Transferable tran = null; try { //The parameter to getContents is not currently used so null should //be sent. If the clipboard is currently not available (for example //it is used by another application) the method throws an //IllegalStateException. tran = clipboard.getContents(null); } catch (IllegalStateException ex) { System.out.println("The clipboard is unavailable."); return; } if (tran != null && tran.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { String clipboardContent = (String)tran.getTransferData(DataFlavor.stringFlavor); System.out.println(clipboardContent); } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } } public static void main(String[] args) { new Main().displayTextFromClipboard(); } } |