我在SINGLE_SELECTION模式下设置了JTable,即用户一次只能选择一行。 我试图覆盖 CTRL + C KeyListener,以便将整个表复制到剪贴板。
目前,我已在其构造函数中为JTable本身添加了一个KeyListener:
public MyTable(AbstractTableModel model) {
super(model);
getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
addKeyListener(new ExcelClipboardKeyAdapter(this));
}
KeyListener如下所示:
public class ExcelClipboardKeyAdapter extends KeyAdapter {
private static final String LINE_BREAK = System.lineSeparator();
private static final String CELL_BREAK = "\t";
private static final Clipboard CLIPBOARD = Toolkit.getDefaultToolkit().getSystemClipboard();
private final JTable table;
public ExcelClipboardKeyAdapter(JTable table) {
this.table = table;
}
@Override
public void keyReleased(KeyEvent event) {
if (event.isControlDown()) {
if (event.getKeyCode() == KeyEvent.VK_C) { // Copy
copyToClipboard();
System.out.println("here");
}
}
}
private void copyToClipboard() {
int numCols = table.getColumnCount();
int numRows = table.getRowCount();
StringBuilder excelStr = new StringBuilder();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
excelStr.append(escape(table.getValueAt(i, j)));
if (j < numCols - 1) {
excelStr.append(CELL_BREAK);
}
}
excelStr.append(LINE_BREAK);
}
StringSelection sel = new StringSelection(excelStr.toString());
CLIPBOARD.setContents(sel, sel);
}
private String escape(Object cell) {
return (cell == null? "" : cell.toString().replace(LINE_BREAK, " ").replace(CELL_BREAK, " "));
}
}
但是,当我按 CTRL + C 时,keyreleased
方法未被调用,并且不会打印“here”。剪贴板的内容仅包含选定的行。
欢迎任何想法。
修改
实际上它有时会工作几次然后停止工作并再次复制一行......很奇怪......
答案 0 :(得分:3)
将我的评论转移到答案中:
实现一个自定义的TransferHandler,它创建“excel-transferable”并在表中使用它(使用dragEnabled == true) - 适合目标操作系统的键绑定 - 然后自动连线
答案 1 :(得分:2)
1)使用KeyBundings
而不是KeyListener
,因为Focus和setFosusable没有任何问题
2)你能解释为什么你需要以这种方式确定SystemClipboard
的原因,也许还有另一种方式