Copying to global clipboard does not work with Java in Ubuntu

前端 未结 4 1138
悲哀的现实
悲哀的现实 2020-12-08 04:58

The following code from a standalone application works in ubuntu:

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransf         


        
4条回答
  •  -上瘾入骨i
    2020-12-08 05:31

    I tried your code with debian testing (7.0) and openjdk 7u3. The result is the same, but i think i found the Problem (Solution).

    Content in the clipboard is only valid as long as the process exists. It works if i change your code to this:

    import java.awt.Toolkit;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.StringSelection;
    import java.awt.datatransfer.Transferable;
    
    public class ClipboardTest {
    
        public static void main(String[] args) throws Exception {
            Clipboard clipBoard = Toolkit.getDefaultToolkit().getSystemClipboard();
            // print the last copied thing
            Transferable t = clipBoard.getContents(null);
            if (t.isDataFlavorSupported(DataFlavor.stringFlavor))
                System.out.println(t.getTransferData(DataFlavor.stringFlavor));
            StringSelection data = new StringSelection("NOW");
            clipBoard.setContents(data, data);
            // prints NOW
            System.out.println(clipBoard.getContents(null).getTransferData(DataFlavor.stringFlavor));
            System.in.read();
        }
    }
    

    The if statement prevent your code from throwing an exception when there is no usable content, which happens if you run your code once and the process ends.
    The System.in.read() just keeps the process alive. While not press enter i can paste into another application and "NOW" comes out as expected.
    Like this the code works every time for me.

    Hope this helps.

提交回复
热议问题