将单元格数据从TableView复制到剪贴板

时间:2016-01-12 16:29:07

标签: javafx-8

我有一个TableView,它取决于用户输入 - 4到10列。我希望能够将选定的单元格复制到系统剪贴板。我尝试了在SO中找到的这段代码,但是position.getColumn()总是返回-1,所以它不起作用。此外,table.getSelectionModel().getSelectedCells()仅返回与行数相同的项目。我希望它每个单元格返回一个项目。有人可以指出我的错误吗?

TableView<TableEntry> table = new TableView<>();
        //copy to clipboard
        table.setOnKeyPressed(e -> {
            if (e.getCode() == KeyCode.C && e.isControlDown()) {
                StringBuilder clipboardString = new StringBuilder();

                ObservableList<TablePosition> positionList = table.getSelectionModel().getSelectedCells();

                int prevRow = -1;

                for (TablePosition position : positionList) {

                    int row = position.getRow();
                    int col = position.getColumn();


                    Object cell = (Object) table.getColumns().get(col).getCellData(row);

                    // null-check: provide empty string for nulls
                    if (cell == null) {
                        cell = "";
                    }

                    // determine whether we advance in a row (tab) or a column
                    // (newline).
                    if (prevRow == row) {

                        clipboardString.append('\t');

                    } else if (prevRow != -1) {

                        clipboardString.append('\n');

                    }

                    // create string from cell
                    String text = cell.toString();

                    // add new item to clipboard
                    clipboardString.append(text);

                    // remember previous
                    prevRow = row;
                }

                // create clipboard content
                final ClipboardContent clipboardContent = new ClipboardContent();
                clipboardContent.putString(clipboardString.toString());

                // set clipboard content
                Clipboard.getSystemClipboard().setContent(clipboardContent);
            }

        });

2 个答案:

答案 0 :(得分:0)

James_D在评论中将其钉在了一起;需要启用单元格选择:

table.getSelectionModel().setCellSelectionEnabled(true)

答案 1 :(得分:0)

这是useful link 这就是我的答案:

    @FXML
    public void copyText() {
        String elementTableSelected = messageTable.getSelectionModel().getSelectedItem().getNotificationsLanguage().esProperty().getValue();
        final Clipboard clipboard = Clipboard.getSystemClipboard();
        final ClipboardContent content = new ClipboardContent();
        content.putString(elementTableSelected);
        clipboard.setContent(content);
        System.out.println(elementTableSelected);
    }