Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow user to copy data from TableView

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);
like image 493
clay Avatar asked Aug 06 '14 21:08

clay


1 Answers

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.

like image 66
Mansueli Avatar answered Sep 22 '22 13:09

Mansueli