Java Swing - 以编程方式从 JTable 复制到剪贴板

发布于 2024-10-06 00:13:12 字数 354 浏览 0 评论 0原文

我想在我的 UI 中添加一个按钮,将特定表的内容复制到剪贴板。我认为这应该很容易,但我似乎无法让它工作或在互联网上找到解决方案。我尝试过这个:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
ActionEvent nev = new ActionEvent(fileTable, ActionEvent.ACTION_PERFORMED, "copy");
TransferHandler.getCopyAction().actionPerformed(nev);
}

但没有效果。 实现这一目标的最佳方法是什么? 谢谢, 彼得

I would like to add a button to my UI which copies the contents of a specific table to the clipboard. I think this should be easy but I can't seem to get it to work or find the solution on the internet. I tried this:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
ActionEvent nev = new ActionEvent(fileTable, ActionEvent.ACTION_PERFORMED, "copy");
TransferHandler.getCopyAction().actionPerformed(nev);
}

but it has no effect.
What's the best way to achieve this?
Thanks,
Peter

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

玩世 2024-10-13 00:13:12

所有 Swing 组件都包含由 KeyStrokes 调用的操作。您可以重复使用此操作。

Action copy = table.getActionMap().get("copy");
ActionEvent ae = new ActionEvent(table, ActionEvent.ACTION_PERFORMED, "");
copy.actionPerformed(ae);

有关所有操作的列表,请查看按键绑定

All Swing components contain Actions that invoked by KeyStrokes. You can reuse this Action.

Action copy = table.getActionMap().get("copy");
ActionEvent ae = new ActionEvent(table, ActionEvent.ACTION_PERFORMED, "");
copy.actionPerformed(ae);

For a list of all Actions check out the Key Bindings.

以往的大感动 2024-10-13 00:13:12

感谢所有回答的人。我使用调试器对 Swing 代码进行了一些跟踪。我相信我发布的代码和 camickr 发布的代码最终会做基本上相同的事情。问题是我假设表中的“不选择”会复制所有内容。事实上,它是一个无操作 - 如果有人感兴趣的话,它位于 BasicTableUI.java 中。所以这段代码确实有效:

ActionEvent nev = new ActionEvent(fileTable, ActionEvent.ACTION_PERFORMED, "copy");
fileTable.selectAll();
fileTable.getActionMap().get(nev.getActionCommand()).actionPerformed(nev);

在我的实际代码中,我添加了几行来在 selectAll() 之前保存当前选择,然后恢复它。

Thanks to all who answered. I did some tracing through the Swing code with the debugger. I believe the code I posted and what camickr posted end up doing basically the same thing. The problem was that I assumed that 'no selection' in the table would copy everything. In fact it's a no-op - this is in BasicTableUI.java if anyone is interested. So this code does work:

ActionEvent nev = new ActionEvent(fileTable, ActionEvent.ACTION_PERFORMED, "copy");
fileTable.selectAll();
fileTable.getActionMap().get(nev.getActionCommand()).actionPerformed(nev);

In my actual code I've added lines to save the current selection before selectAll() and then restore it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文