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

When my Java-based application (and not the browser-based applet) copies plain text to the Linux system clipboard, many programs cannot access the clipboard data, but some of them.

Here is the simplest test I could do:

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) has access to the text that it places on the system clipboard. But using File> Paste in Gnome Terminal, Mozilla Thunderbird and Firefox and many other programs cannot. The Paste option is gray, as if the clipboard is empty.

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

+4
source share
1 answer

Your code is ok. His problem is that it ends too soon.

In window system X, a process that places something in the clipboard (that is, a selection with the name clipboard) must remain alive so that the copied data is saved. ( Read about active and passive buffers and note that the choice is active ).

While your process is running, i.e. sleep() s, you can insert data anywhere. Once it completes, the clipboard is empty.

This is not a special Java behavior; You can easily play it using charmap or any other program that you don't mind closing.

I do not know how LibreOffice scored a point in your test. Perhaps this was the first on your alt + list. In my tests, LibreOffice behaved like any other application: "paste" worked as long as the Java process was active, and stopped working when the process terminated.

I do not know how to fix this in the general case. Perhaps the clipboard manager will help (which remembers several elements being copied and probably owns all of them).

+3
source

All Articles