Is it possible to be informed when clipboard conte

2019-03-24 17:07发布

The thing I would want to do is that when the user copies a text in any program (firefox, notepad, pdfReader etc.) my already running java application shall be informed and immediately shows a popup.

I think in order to be able to do this my java application should be invoked whenever system clipboard is changes.

Is that possible with java, if so in which version? I know we can reach and manipulate system clipboard content but my specific question is about invoking the java app. when clipboard content changes.

Thanks

1条回答
男人必须洒脱
2楼-- · 2019-03-24 17:24

I would have naively pretended it's a job for JDIC, but the interwebz told me the truth. So, let me explain a little.

using Toolkit.getSystemClipboard(), you can get access to the native system clipboard. Like any Java object, this clipboard can be listened. Precisely, you can call Clipboard.addFlavorListener(...) to listen to FlavorEvents. What are they ? They're the metal kings ! .... no no no, I completely and utterly digress. Let me come back. So, a FlavorEvent, according to the doc, indicates that

that available DataFlavors have changed in the Clipboard (the event source).

Which may means that Clipboard content has changed. However, I would not go directly on it without a first prototype.

EDIT Example of a prototype from the fingers of AlexR

import java.awt.Toolkit;
import java.awt.datatransfer.FlavorEvent;
import java.awt.datatransfer.FlavorListener;

public class Main {
    public static void main(String[] args) throws Exception { 
        Toolkit.getDefaultToolkit().getSystemClipboard().addFlavorListener(new FlavorListener() { 
            @Override 
            public void flavorsChanged(FlavorEvent e) { 
                System.out.println("changed!!! " + e.getSource() + " " + e.toString()); 
            } 
        }); 
        Thread.sleep(100000L); 
    }
}
查看更多
登录 后发表回答