我正在开发一个 Java 应用程序,当我在 jTable 上按 CTRL+C 时,我可以获取剪贴板并将其粘贴到 Excel 中。我想实现一个做同样事情的按钮。我怎样才能得到函数,监听器,无论我用什么来实现这个?
PS:我尝试过查看其他问题,但似乎没有人在寻找我想要的东西。
表的复制操作的关键是"copy"
:
Action copyAction = table.getActionMap().get("copy");
但我没有看到一种有用的方法来回收Action
:
JButton button = new JButton(copyAction);
相反,只需将表的当前选择导出到系统剪贴板。
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);
附录:此变体依赖于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);
但我没有看到回收动作的有用方法:
您不能以这种方式使用 Action,因为 Action 的来源是按钮而不是表格。
有关通用解决方案,请参阅动作映射动作。使用提供的类,代码将是:
Action copyAction = new ActionMapAction("Copy Table", table, "copy");
JButton copyButton = new JButton(copyAction);