Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving string from clipboard in Java

Tags:

java

I am trying to get some text from the clipboard using this method, but it throws an exception into the string instead of the text.

Am I just doing it wrong or something?

Transferable t = cb.getContents(null);
String begin = t.toString();
System.out.println("Successfully fetched:");
System.out.println(begin);

Throws this error:

sun.awt.datatransfer.ClipboardTransferable@6d03e736

like image 760
Reggie Peck Avatar asked Dec 13 '25 16:12

Reggie Peck


1 Answers

Try this code snippet which attempts to retrieve a String from the System clipboard:

String result = "";
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
boolean hasStringText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor);
if (hasStringText) {
    try {
        result = (String)contents.getTransferData(DataFlavor.stringFlavor);
    } catch (UnsupportedFlavorException | IOException ex) {
        System.out.println(ex); ex.printStackTrace();
}
like image 92
Tim Biegeleisen Avatar answered Dec 15 '25 08:12

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!