如何使用Java将系统剪贴板内容粘贴到任意窗口 [英] How to paste from system clipboard content to an arbitrary window using Java

查看:155
本文介绍了如何使用Java将系统剪贴板内容粘贴到任意窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个带有按钮的Java程序。当按下按钮时,它将系统剪贴板的内容粘贴/拖放到当前在任意(可能是非Java)应用程序(例如MS Word)中具有焦点的文本字段。本质上,按钮动作必须以某种方式模拟CTRL-V(粘贴)动作的发送。

I would like to write a Java program that has a button. When the button is pressed it pastes / drops the content of the system clipboard to the text field that currently has focus within an arbitrary, possibly non-Java app (say MS Word). Essentially the button action has to simulate the sending of CTRL-V (paste) action somehow.

任何人有任何建议吗?

推荐答案

java.awt.datatransfer 似乎是一种解决方案,根据本文。这是另一篇文章

The package java.awt.datatransfer seems to be a solution, according to this article. Here is another article.

在后面的页面中,需要导入:

From the latter page, the needed imports:

import java.awt.datatransfer.*;
import java.awt.Toolkit;

方法代码如下。解决方案是创建一个侦听器并将其添加到按钮。侦听器只需获取剪贴板的内容并将其插入到所需的任何组件中即可。

And the method code is below. The solution is to create a listener and add it to the button. The listener should simply get the contents of the clipboard and insert it to whatever component you wish.

public void setClipboardContents( String aString ){
  StringSelection stringSelection = new StringSelection( aString );
  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
  clipboard.setContents( stringSelection, this );
}

public String getClipboardContents() {
  String result = "";
  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
  //odd: the Object param of getContents is not currently used
  Transferable contents = clipboard.getContents(null);
  boolean hasTransferableText =
    (contents != null) &&
    contents.isDataFlavorSupported(DataFlavor.stringFlavor)
  ;
  if ( hasTransferableText ) {
    try {
      result = (String)contents.getTransferData(DataFlavor.stringFlavor);
    }
    catch (UnsupportedFlavorException ex){
      //highly unlikely since we are using a standard DataFlavor
      System.out.println(ex);
      ex.printStackTrace();
    }
    catch (IOException ex) {
      System.out.println(ex);
      ex.printStackTrace();
    }
  }
  return result;
}

这篇关于如何使用Java将系统剪贴板内容粘贴到任意窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆