2012-04-06 41 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 
     } 
    } 
    } 

我添加了一些简单的可测试性/验证轮询。它会每秒钟检查剪贴板一次。据我所知,没有办法做基于事件的通知(除非你正在倾听味道的变化,你不知道),所以我认为你坚持投票。