7

如何清除System ClipboardJava中的?我努力了

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

但它只是抛出了一个NPE

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: contents
    at sun.awt.datatransfer.SunClipboard.setContents(SunClipboard.java:98)
4

2 回答 2

10

您可以创建一个Transferable明确不包含数据的特殊内容,如本博文中所述:

  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);
    }
于 2013-08-15T14:31:15.410 回答
6

你可以这样做:

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

自从StringSelection implements Transferable

public class StringSelection implements Transferable, ClipboardOwner
于 2013-08-15T14:31:27.297 回答