简体   繁体   中英

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. 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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