复制所选 JTable 单元格而不是行的单元格值

Copying the cell value of selected JTable cell instead of row

我试图在 Jtable 的实际单元格而不是整行上启用 ctrl c。我知道如何禁用整行的 ctrl c。

KeyStroke cStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK);
inputMap.put(cStroke,  "none");

我尝试了以下方法来向单元格本身添加一个 ctrl c:向 table 本身添加一个 keylistener。那没起效。以及以下代码:

Action actionListener = new AbstractAction() {
    public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("activated");
    }
};
KeyStroke cStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK);
inputMap.put(cStroke,  actionListener);

它没有打印激活。

我已阅读 JTable: override CTRL+C behaviour 但它不包含答案,至少不是具体答案..

您可以像这样将所选单元格的内容复制到剪贴板:

import javax.swing.*;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;

public class CopyCell
{
  public static void main(String[] args)
  {
    JTable table = new JTable(
        new String[][] {{"R1C1", "R1C2"}, {"R2C1", "R2C2"}},
        new String[] {"Column 1", "Column 2"});

    table.getActionMap().put("copy", new AbstractAction()
    {
      @Override
      public void actionPerformed(ActionEvent e)
      {
        String cellValue = table.getModel().getValueAt(table.getSelectedRow(), table.getSelectedColumn()).toString();
        StringSelection stringSelection = new StringSelection(cellValue);
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, stringSelection);
      }
    });

    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new JScrollPane(table));
    f.setBounds(300, 200, 400, 300);
    f.setVisible(true);
  }
}