Is it possible to allow a user to select rows and copy from a TableView?
tableView.getSelectionModel().setCellSelectionEnabled(true);
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
MenuItem item = new MenuItem("Copy");
item.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
ObservableList<TablePosition> posList = tableView.getSelectionModel().getSelectedCells();
int old_r = -1;
StringBuilder clipboardString = new StringBuilder();
for (TablePosition p : posList) {
int r = p.getRow();
int c = p.getColumn();
Object cell = tableView.getColumns().get(c).getCellData(r);
if (cell == null)
cell = "";
if (old_r == r)
clipboardString.append('\t');
else if (old_r != -1)
clipboardString.append('\n');
clipboardString.append(cell);
old_r = r;
}
final ClipboardContent content = new ClipboardContent();
content.putString(clipboardString.toString());
Clipboard.getSystemClipboard().setContent(content);
}
});
ContextMenu menu = new ContextMenu();
menu.getItems().add(item);
tableView.setContextMenu(menu);