简体   繁体   English

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

[英]Java Swing - programmatically copy to clipboard from a JTable

I would like to add a button to my UI which copies the contents of a specific table to the clipboard. 我想在我的UI中添加一个按钮,该按钮将特定表的内容复制到剪贴板。 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 谢谢彼得

All Swing components contain Actions that invoked by KeyStrokes. 所有Swing组件都包含由KeyStrokes调用的Action。 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 . 有关所有操作的列表,请查看“ 键绑定”

Thanks to all who answered. 感谢所有回答。 I did some tracing through the Swing code with the debugger. 我使用调试器对Swing代码进行了一些跟踪。 I believe the code I posted and what camickr posted end up doing basically the same thing. 我相信我发布的代码和camickr发布的内容最终会做同样的事情。 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. 实际上,这是一项禁止操作的操作-如果有人感兴趣的话,它位于BasicTableUI.java中。 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. 在我的实际代码中,我添加了selectAll()行以在selectAll()之前保存当前选择,然后将其还原。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM