如何清除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)
答案 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