JTable: override CTRL + C behavior

I have a JTable set in SINGLE_SELECTION mode, i.e. the user can select only one row at a time. I am trying to override CTRL + C KeyListener to copy the entire table to the clipboard.

Currently, I have added KeyListener to JTable itself in my constructor:

public MyTable(AbstractTableModel model) { super(model); getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); addKeyListener(new ExcelClipboardKeyAdapter(this)); } 

KeyListener is as follows:

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

However, when I press CTRL + C , the keyreleased method keyreleased not called and does not print "here." The contents of the clipboard contains only the selected line.

Any ideas are welcome.

EDIT

Actually it sometimes works several times, then it stops working and again copies one line ... weird ...

+4
source share
2 answers

Wrap my comment in response:

implement a custom TransferHandler that creates an "excel-transferable" and use it in the table (with dragEnabled == true) - a key binding suitable for the target OS - then automatically connects

+3
source

1) use KeyBundings , not KeyListener , because there is no problem with Focus and setFosusable

2) can you explain the reason why you needed to define SystemClipboard in this way, maybe there is / is another way (s)

+2
source

Source: https://habr.com/ru/post/1398830/


All Articles