Error handling for the clipboard

I am using the following code to capture text from the clipboard, however if I use print screen the clipboard will be filled with image data and return an error.

Object getFromClipboard (DataFlavor flavor) {

  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); 
  Transferable contents = clipboard.getContents(null);
  Object object = null;

  if (contents != null && contents.isDataFlavorSupported(flavor))
  {
    try
    {
      object = contents.getTransferData(flavor);
      println("Clipboard.getFromClipboard() >> Object transferred from clipboard.");
    }

    catch (UnsupportedFlavorException e1) // Unlikely but we must catch it
    {
      println("Clipboard.getFromClipboard() >> Unsupported flavor: " + e1);
      //~  e1.printStackTrace();
    }

    catch (java.io.IOException e2)
    {
      println("Clipboard.getFromClipboard() >> Unavailable data: " + e2);
      //~  e2.printStackTrace();
    }
  }

  return object;
}

String getTextFromClipboard () {
  String text = (String) getFromClipboard(DataFlavor.stringFlavor);
 
  if (text==null) 
    return "";
 
  return text;
}

How do I implement error handling to deal with this eventuality?

it seems the line in question is this one

Transferable contents = clipboard.getContents(null);

It would be better to implement this code in a class. G4P has a class, GClip, to handle copying and pasting of text, you might try incorporating this class in your sketch.

1 Like

What OS are you using for this? I am not able to repro using P3.5.3 and Win10x64. I have

void mouseReleased() {
  print(getTextFromClipboard());
}

and if I have an image capture using the prtScr key, the code does not execute as no error is thrown. If you get an error, you are saying that the line

Transferable contents = clipboard.getContents(null);

gets highlighted by the PDE?

Kf

thats it, Iā€™m using windows 10, with the latest version of processing