Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the system clipboard in Java?

Tags:

java

clipboard

How can I clear the System Clipboard in Java? I have tried

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(null, null);

but it just had thrown an NPE:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: contents
    at sun.awt.datatransfer.SunClipboard.setContents(SunClipboard.java:98)
like image 225
SeniorJD Avatar asked Aug 15 '13 14:08

SeniorJD


2 Answers

You can create a special Transferable that explicitly contains no data, as detailed in this blog post:

  clipboard.setContents(new Transferable() {
    public DataFlavor[] getTransferDataFlavors() {
      return new DataFlavor[0];
    }

    public boolean isDataFlavorSupported(DataFlavor flavor) {
      return false;
    }

    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
      throw new UnsupportedFlavorException(flavor);
    }
like image 162
Joey Avatar answered Oct 21 '22 17:10

Joey


You can do this:

StringSelection stringSelection = new StringSelection("");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(
            stringSelection, null);

Since StringSelection implements Transferable

public class StringSelection implements Transferable, ClipboardOwner
like image 42
Tala Avatar answered Oct 21 '22 18:10

Tala