Allow user to copy data from TableView

2019-04-07 19:43发布

I have a simple JavaFX app that allows the user to query a database and see the data in a table.

I'd like to allow the user to be able to click a table cell and copy text from that cell to the clipboard with the standard clipboard key stroke: ctrl-c for Win/Linux or cmd-c for Mac. FYI, the text entry controls support basic copy/paste by default.

I'm using the standard javafx.scene.control.TableView class. Is there a simple way to enable cell copy? I did some searches and I see other people create custom menu commands... I don't want to create a custom menu, I just want basic keyboard copy to work with single cells.

I'm using single selection mode, but I can change to something else if need be:

    TableView<Document> tableView = new TableView<Document>();
    tableView.getSelectionModel().setCellSelectionEnabled(true);
    tableView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-07 19:52

You just have to create a listener in the scene, something like:

scene.getAccelerators()
.put(new KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_ANY), new Runnable() {
    @Override
    public void run() {
        int row = table.getSelectionModel().getSelectedIndex();
        DataRow tmp = table.getItems().get(row);
        final Clipboard clipboard = Clipboard.getSystemClipboard();
        final ClipboardContent content = new ClipboardContent();
        if(table.getSelectionModel().isSelected(row, numColumn)){
            System.out.println(tmp.getNumSlices());
            content.putString(tmp.getNumSlices().toString());
        }
        else{
            System.out.println(tmp.getSelected());
            content.putString(tmp.getSelected());
        }
        clipboard.setContent(content);
    }
});

For a complete example, you can download it at the gist.

查看更多
贪生不怕死
3楼-- · 2019-04-07 19:52

I recommended that you review this post, work for me

http://respostas.guj.com.br/47439-habilitar-copypaste-tableview-funcionando-duvida-editar-funcionalidade

The author use an aditional util java class for enable the cell content copy from a tableView

查看更多
登录 后发表回答