The key for the table's copy action is "copy"
:
Action copyAction = table.getActionMap().get("copy");
But I don't see a useful way to recycle the Action
:
JButton button = new JButton(copyAction);
Instead, just export the table's current selection to the system clipboard.
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableModel model = new DefaultTableModel(
new Object[][]{{"Some"}, {"More"}}, new Object[]{"Name"});
final JTable table = new JTable(model);
table.getSelectionModel().setSelectionInterval(0, 1);
f.add(table);
f.add(new JButton(new AbstractAction("Export") {
@Override
public void actionPerformed(ActionEvent e) {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
table.getTransferHandler().exportToClipboard(
table, clipboard, TransferHandler.COPY);
Transferable contents = clipboard.getContents(null);
}
}), BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
Addendum: This variation relies on TableTransferable
.
final DefaultTableModel model = new DefaultTableModel(
new Object[][]{
{"A1", "A2", "A3", "A4", "A5"},
{"B1", "B2", "B3", "B4", "B5"},
{"C1", "C2", "C3", "C4", "C5"},
{"D1", "D2", "D3", "D4", "D5"},
{"E1", "E2", "E3", "E4", "E5"},
{"F1", "F2", "F3", "F4", "F5"}
},
new Object[]{"1", "2", "3", "4", "5"});
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTable table = new JTable(model);
table.getSelectionModel().setSelectionInterval(0, 1);
f.add(table);
f.add(new JButton(new AbstractAction("Export") {
@Override
public void actionPerformed(ActionEvent e) {
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
cb.setContents(new TableTransferable(model), new ClipboardOwner() {
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("Clipboard lost!");
}
});
}
}), BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);