如何将String复制到java中的系统剪贴板?

Mag*_*y52 0 java clipboard swing awt

我有一个JTextArea并且想要一个按钮,当点击它时会将整个内容复制JTextAreaSystem剪贴板,这样我就可以在任何其他程序中执行Ctrl-V.我试过这个,但没有运气.这是我尝试过的一个例子:

StringSelection stringSelection = new StringSelection("This is a clipping");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents( stringSelection, null );
Run Code Online (Sandbox Code Playgroud)

Rei*_*eus 5

ClipBoard需要ClipboardOwner才能使复制操作生效.此接口通常由当前的"粘贴"类实现:

clipboard.setContents( stringSelection, myClipboardOwner);
Run Code Online (Sandbox Code Playgroud)