Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 514
nestorrente Avatar asked Mar 17 '26 06:03

nestorrente


1 Answers

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
like image 97
Rubasace Avatar answered Mar 18 '26 21:03

Rubasace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!