首页 > 解决方案 > 复制所选 JTable 单元格的单元格值而不是行

问题描述

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

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

我尝试了以下方法将 ctrl c 添加到单元格本身:将 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 behavior但它不包含答案,至少不包含特定答案..

标签: javaswingjtablekeystroke

解决方案


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

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);
  }
}

推荐阅读