java - 复制所选 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但它不包含答案,至少不包含特定答案..
解决方案
您可以像这样将选定单元格的内容复制到剪贴板:
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);
}
}
推荐阅读
- php - 如何从数组中排除某些元素
- python - Django OpenCV 异常值:libSM.so.6:无法打开共享对象文件:没有这样的文件或目录
- python-3.x - 如何计算一组行的唯一值并使用该值为所有记录创建列?
- javascript - 反应切换 ID
- google-cloud-platform - 如何加快 AI 平台训练作业队列?
- c++ - Asio 点对点网络编程
- react-native - 从未定义中获取错误不是对象(评估“navigation.navigate”)
- ramda.js - Ramda - extract object from array
- snowflake-cloud-data-platform - 重新集群表会改变 Snowflake 中的微分区吗?
- database - 当两个用户选择一个产品时,如何设计逻辑或数据库?