如何在Java中清除系统剪贴板?

时间:2013-08-15 14:25:19

标签: java clipboard

如何清除Java中的System Clipboard?我试过了

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)

2 个答案:

答案 0 :(得分:9)

您可以创建一个明确不包含任何数据的特殊Transferable,详细信息为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);
    }

答案 1 :(得分:4)

你可以这样做:

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

StringSelection implements Transferable

以来
public class StringSelection implements Transferable, ClipboardOwner