I found another solution to this problem: the next listener constantly reads the contents of the clipboard using a loop. If text is found, it will be compared with the previous contents of the clipboard that is cached. When the clipboard contains new text that has not previously been cached, it can perform some actions, such as โnotify observers,โ as in this example, which may cause the GUI to refresh.
In this example, content changes when the clipboard contains something other than a string are ignored.
In addition to detecting content type changes (i.e., using FlavorListerner), this solution detects changes by continuously comparing strings. Just by reading access to the clipboard, I would expect this code to cause less interference to other applications than, for example, if it becomes the owner of the clipboard.
Suggestions are welcome.
package gui; import java.awt.HeadlessException; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Observable; class ClipboardTextListener extends Observable implements Runnable { Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard(); private volatile boolean running = true; public void terminate() { running = false; } public void run() { System.out.println("Listening to clipboard...");
source share