gpt4 book ai didi

java - 从 swing 复制并粘贴到其他 Windows 应用程序中

转载 作者:行者123 更新时间:2023-11-30 03:35:09 25 4
gpt4 key购买 nike

我已经搜索了一段时间,但没有显示令人满意的结果,因此想在这里询问。

基本上我有一个 JAVA Swing GUI 表,它有一些行,假设每行 3 列,您会在一行上看到“1 david good”。该行的内容是从原始消息(即 xml 消息)转换而来的。

我想要做的是,当我选择一行并按 ctrl+c 时,可以将原始消息复制到剪贴板,然后我可以将其粘贴到其他 Windows 应用程序(如记事本或 Word)中。

我尝试使用工具包来获取系统剪贴板并将原始消息放入(通过按键监听器)。但是当我在记事本中按 ctrl+v 时,我仍然默认得到“1 david good”。

我在 Swing 代码中打印了剪贴板中的原始消息,因此我猜测我的代码是否只能在 Swing 中运行,在 Windows 中无法检索自定义内容?

有人可以告诉我这是否可以在 Swing 中实现吗?非常感谢。

最佳答案

您可以使用这个示例:

String str = "Which String to copy to clipboard";
StringSelection stringSelection = new StringSelection (str);
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard ();
clpbrd.setContents (stringSelection, null);

因此,当单击某个按钮并从 actionPerformed() 调用它时,可以使用此代码

对于粘贴问题:

  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 | IOException ex){
System.out.println(ex);
ex.printStackTrace();
}
}
return result;
}

关于java - 从 swing 复制并粘贴到其他 Windows 应用程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28169266/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com