什么是JTable CTRL + C事件的名称?

时间:2013-01-16 11:02:59

标签: java swing events jtable clipboard

我正在开发一个Java应用程序,当我在jTable上按CTRL + C时,我可以获取剪贴板并将其粘贴到Excel中。我想实现一个执行相同操作的按钮。我怎样才能获得函数,监听器,无论我用它来实现这个目标?

PS:我曾尝试过查看其他问题,但似乎没有人在寻找我想要的东西。

2 个答案:

答案 0 :(得分:4)

表格复制操作的关键是"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);

答案 1 :(得分:3)

  

但我没有看到回收行动的有用方法:

您不能以这种方式使用Action,因为Action的源是按钮而不是表。

有关一般解决方案,请参阅Action Map Action。使用提供的类代码将是:

Action copyAction = new ActionMapAction("Copy Table", table, "copy");
JButton copyButton = new JButton(copyAction);