Search code examples
javaclipboardkeep-alive

Java - How to keep JVM running while listening to clipboard changes?


I'm writing a program that listens to clipboard changes and print that changes to stdout (it's just a test for a bigger program). The problem is: when the main thread finishes, the JVM exits and no events arrive to the listener. How can I do to keep JVM running while listening the clipboard?

My code looks like this:

public class Test {

    public static void main(String[] args) {

        Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();

        cb.addFlavorListener(new FlavorListener() {
            @Override
            public void flavorsChanged(FlavorEvent e) {
                System.out.println(e);
            }
        });

    } 

}

Thanks!


Solution

  • How can I do to keep JVM running while listening the clipboard?

    I can't see how you would tell the program to stop listening to the clipboard in a proper way.

    What I would do is just print some kind of message using standard out indicating a key to exit the program and then calling a scanner or similiar for checking the input. This way you achieve 2 important points:

    1. The thread doesn't die inmediately as the scanner does the "wait" part I think you are looking for.
    2. Users get control over the thread's lifecycle, so they can terminate it whenever they want in a proper way