Search code examples
javawindowsclipboard

Windows Clipboard Java Program Does Not Work


I want to edit the contents of the Windows clipboard, so that leading and trailing whitespace are removed when inserting the text.

For example, if I copy the text " Hello World ", it should insert "Hello World".

I tried this code:

public class ClipBoardListener extends Thread implements ClipboardOwner{
    
Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();  


  public void run() {
    Transferable trans = sysClip.getContents(this);  
    TakeOwnership(trans);       
    while(true) {
    }
  }  

    public void lostOwnership(Clipboard c, Transferable t) {  

  try {  
      ClipBoardListener.sleep(250);  //waiting e.g for loading huge elements like word's etc.
  } catch(Exception e) {  
    System.out.println("Exception: " + e);  
  }  
  Transferable contents = sysClip.getContents(this);  
    try {
        process_clipboard(contents, c);
    } catch (Exception ex) {
        Logger.getLogger(ClipBoardListener.class.getName()).log(Level.SEVERE, null, ex);
    }
  TakeOwnership(contents);


}  

  void TakeOwnership(Transferable t) {  
    sysClip.setContents(t, this);  
  }  

public void process_clipboard(Transferable t, Clipboard c) { //your implementation
    String tempText;
    Transferable trans = t;

    try {
        if (trans != null?trans.isDataFlavorSupported(DataFlavor.stringFlavor):false) {
            tempText = (String) trans.getTransferData(DataFlavor.stringFlavor);
            
           addStringToClipBoard(tempText);
            
           
        }

    } catch (Exception e) {
    }
}
public static void addStringToClipBoard(String cache) {                         
    StringSelection selection = new StringSelection(cache.trim());
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(selection,null);
}


public static void main(String[] args) {
    
    ClipBoardListener c = new ClipBoardListener();
    c.start();
        
 }  
}

But it doesn't work. How can I fix the problem?


Solution

  • Comment out the TakeOwnership line inside lostOwnership(). It resets the original clipboard contents that you have just changed inside the preceeding process_clipboard call.

    //TakeOwnership(contents);
    

    And make this non-static / use "this":

    public void addStringToClipBoard(String cache) {
      StringSelection selection = new StringSelection(cache.trim());
      Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
      clipboard.setContents(selection,this);
    }
    

    In this example your class does not need to be a Thread as you can call c.run() directly in main. Methods with a tight CPU loop while(true) {} are not a good idea - wait on some exit condition.