The yelliver solution only copies the contents of the selected cells, but apparently only those cells that were explicitly pressed are selected. The Roberto solution only works if the objects stored in the table are iterable. Here is a general solution that copies data from all cells in all selected rows:
@SuppressWarnings("rawtypes") public void copySelectionToClipboard(final TableView<?> table) { final Set<Integer> rows = new TreeSet<>(); for (final TablePosition tablePosition : table.getSelectionModel().getSelectedCells()) { rows.add(tablePosition.getRow()); } final StringBuilder strb = new StringBuilder(); boolean firstRow = true; for (final Integer row : rows) { if (!firstRow) { strb.append('\n'); } firstRow = false; boolean firstCol = true; for (final TableColumn<?, ?> column : table.getColumns()) { if (!firstCol) { strb.append('\t'); } firstCol = false; final Object cellData = column.getCellData(row); strb.append(cellData == null ? "" : cellData.toString()); } } final ClipboardContent clipboardContent = new ClipboardContent(); clipboardContent.putString(strb.toString()); Clipboard.getSystemClipboard().setContent(clipboardContent); }
To enable copying with Ctrl + C, add
final KeyCodeCombination keyCodeCopy = new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_ANY); table.setOnKeyPressed(event -> { if (keyCodeCopy.match(event)) { copySelectionToClipboard(table); } });
source share