How to allow selection and copying of data from TableVIew to JavaFX? By default, only one line is selected there, which cannot be copied via Ctrl + C
1 answer
To select several rows in a table, you need to set the table with
tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);For copying to work, you must implement this functionality yourself. To do this, you need to handle keystrokes for a table. Example code The Bean class is responsible for setting the table.
class Bean { String name; int count; }
And the table itself is created and click processing
TableView < Bean > tableView = new TableView < > (); tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); tableView.setOnKeyPressed(e - > { if (e.isControlDown() && e.getCode() == KeyCode.C) { ObservableList < Bean > selectedItems = tableView.getSelectionModel().getSelectedItems(); //получаем список выделенных строк и копируем их, например - через точку с запятой, как в excel'e String copyString = selectedItems .stream() .map(bean - > bean.name + ";" + bean.count) .collect(Collectors.joining(System.lineSeparator())); //далее сохраняем это в буфер обмена StringSelection stringSelection = new StringSelection(copyString); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null); } }); |