2012-04-06 68 views
1

我試圖讓一個應用程序存儲聲明 - 在某個階段 - 存儲所有報表由CTRL +Ç複製和操作的「緩衝」攜帶當前語句具體聲明緩衝攜帶用Ctrl + C

例如:用戶按下CTRL + ç複製的「你好」,如果他按下CTRL + V在任何文本區域/領域的文字是「你好」,我希望書面聲明是「測試」我而不是「你好」

問題是:如何訪問攜帶複製語句的緩衝區並使用Java處理其內容?

+0

所以你想完全改變操作系統剪貼板的內容?不,謝謝。 – 2012-04-06 21:23:10

+2

可能的重複[複製到剪貼板在Java](http://stackoverflow.com/questions/3591945/copying-to-clipboard-in-java) – 2012-04-06 21:24:14

+0

@ BlueRaja-DannyPflughoeft是的,這是我真正想要的,但不能'不要把它表達得很好,thx – 2012-04-06 22:10:38

回答

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 
     } 
    } 
    } 

我添加了一些簡單的可測試性/驗證輪詢。它會每秒鐘檢查剪貼板一次。據我所知,沒有辦法做基於事件的通知(除非你正在傾聽味道的變化,你不知道),所以我認爲你堅持投票。