6

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);
clay
  • 18,138
  • 28
  • 107
  • 192
  • 1
    See: [Copyable Label/TextField/LabeledText in JavaFX](http://stackoverflow.com/questions/22534067/copiable-label-textfield-labeledtext-in-javafx) and try combining that approach with a custom table cell factory. – jewelsea Aug 06 '14 at 21:37

2 Answers2

4

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.

Mansueli
  • 6,223
  • 8
  • 33
  • 57
2

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

Doberon
  • 611
  • 9
  • 19