1

I'm trying to make an application that - in some stage - stores all the statements copied by CTRL+C , and manipulating the 'buffer' carrying the current statement to a specific statement

example : user pressed CTRL + C to copy the "Hello" , if he presses CTRL + V at any text area/field the written word would be "Hello" , I want the written statement to be "Test" instead of "Hello"

the question is : how to access the buffer carrying the copied statement and manipulate its content using Java ?

Neysor
  • 3,893
  • 11
  • 34
  • 66
a.u.r
  • 1,253
  • 2
  • 21
  • 32

1 Answers1

1
  public static void main(String[] args) throws Exception
  {
    // Get a reference to the clipboard
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

    // Poll once per second for a minute
    for (int i = 0; i < 60; i++)
    {
      // Null is ok, because, according to the javadoc, the parameter is not currently used
      Transferable transferable = clipboard.getContents(null);

      // Ensure that the current contents can be expressed as a String
      if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor))
      {
        // Get clipboard contents and cast to String
        String data = (String) transferable.getTransferData(DataFlavor.stringFlavor);

        if (data.equals("Hello"))
        {
          // Change the contents of the clipboard
          StringSelection selection = new StringSelection("Test");
          clipboard.setContents(selection, selection);
        }
      }

      // Wait for a second before the next poll
      try
      {
        Thread.sleep(1000);
      }
      catch (InterruptedException e)
      {
        // no-op
      }
    }
  }

I added polling for some simple testability/verification. It'll check the clipboard once a second for a minute. As far as I'm aware, there's no way to do event-based notification (unless you're listening for flavor changes, which you're not), so I think you're stuck with polling.

Eric Grunzke
  • 1,487
  • 15
  • 21