Set Clipboard Contents

2020-07-18 04:48发布

I am trying to figure out why setting the contents of the system clipboard won't work for me. I programmatically set the clipboard contents. When i use the output part of the code, it works. However, when i try copy/pasting in any text editor, it is blank.


hovercraft edit, code from github:

import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

public class Test {
   public static void main(String[] args) throws HeadlessException,
         UnsupportedFlavorException, IOException {

      Toolkit.getDefaultToolkit().getSystemClipboard()
            .setContents(new StringSelection("hi there"), null);

      System.out.println(((String) Toolkit.getDefaultToolkit()
            .getSystemClipboard().getData(DataFlavor.stringFlavor)));

   }
}

标签: java linux
2条回答
甜甜的少女心
2楼-- · 2020-07-18 05:20

Linux cut and paste is a bit weird these days, because there are at least two different ways of doing it. In short, sometimes it's better to just paste with the middle button, and other times it's better to control-v, and sometimes neither seems to work.

Running autocutsel as a background process seems to help. http://www.nongnu.org/autocutsel/

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-07-18 05:24
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Clipboard;

public class tester{

 public static void main(String[] args){

     // from string to clipboard
    StringSelection selection = new StringSelection("hi");
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(selection, selection);
 }
}

This program does it. It will set the String "hi" to clipboard. You can change it to a variable.

查看更多
登录 后发表回答