简体   繁体   中英

Java Clipboard on Linux (text only), some programs can read it, others can't, why

When my Java-based application (not a browser-based applet) copies plain text to the system clipboard on Linux, many programs are not able to access the clipboard data, but some are.

Here's the simplest test I could make:

import java.awt.datatransfer.*;
import java.awt.Toolkit;
import java.io.*;

public final class PasteTest {
  public static void main (String...  args) {
    String mytext = "This is a test message, testing, 1, 2, 3....";
    StringSelection sel = new StringSelection(mytext);
    Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
    clip.setContents(sel, null);
    try {
      Thread.sleep(1000);
    } catch (Exception e) {
    }
  }
} 

While this program is running, File > Paste in OpenOffice (LibreOffice 3.5.7.2) is able to access the text it placed on the system clipboard. But using File > Paste in Gnome Terminal, Mozilla Thunderbird & Firefox, and many other programs can not. The Paste option is gray, as if the clipboard is empty.

How can I make my Java program publish plain text to the system clipboard on Linux (testing on Ubuntu 12.04) so all programs can access it?

Your code is fine. Its problem is that it terminates too soon.

Under X window system, the process that puts something on 'clipboard' (that is, the selection named 'clipboard') must stay alive for the copied data to survive. ( Read about active and passive buffers, and notice that selections are of the active kind ).

While your process runs, that is, sleep() s, you can paste the data anywhere. Once it terminates, clipboard goes empty.

This is not special behavior of Java; you can easily reproduce it with charmap or any other program you don't mind closing.

I don't know how LibreOffice scored a point in your test. Possibly it was first on your alt+tab list. In my tests, LibreOffice behaved like any other app: 'paste' worked as long as the Java process was alive, and stopped working as the process terminated.

I don't know how to fix it in general case. Running a clipboard manager (that remembers multiple copied items and thus probably owns all of them) might help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM