Hi, quick question, how can I make a tableview abl...
# tornadofx
w
Hi, quick question, how can I make a tableview able to be copy/pasted into another app, like a text editor? I want to be able to select a whole column, or a whole table and copy the contents out (preferably in csv format)
👍 1
the table contains readonlycolumns
oh, i got it with this:
Copy code
selectionModel.cellSelectionEnabledProperty().value = true
                                selectionModel.selectionMode = SelectionMode.MULTIPLE
not csv though
a
Hey, did you look into OSGI.kt for TornadoFX?? They have that
w
i got csv to work like this:
Copy code
fun TableView<*>.enableCsvCopy() {
    val item = MenuItem("Copy")
    item.action { com.grubhub.ui.copyTable(this) }
    val menu = ContextMenu()
    menu.items.add(item)
    contextMenu = menu
    val keyCodeCopy = KeyCodeCombination(KeyCode.C, KeyCombination.CONTROL_ANY)
    setOnKeyPressed { event ->
        if (keyCodeCopy.match(event)) {
            com.grubhub.ui.copyTable(this)
        }
    }
}


fun copyTable(table: TableView<*>) {
    val posList = table.selectionModel.selectedCells
    val columns = table.columns.joinToString(",") { it.text }
    val csvText = posList.fold(TableFold(-1, columns)) { lastRow, pos ->
        val cell = table.columns.get(pos.column).getCellData(pos.row)
        val separator = if (pos.row == lastRow.row) "," else "\n"
        val cellString = if (cell.toString().contains(",")) "\"${cell ?: ""}\"" else cell
        TableFold(pos.row, "${lastRow.string}$separator$cellString")
    }
    val content = ClipboardContent()
    content.putString(csvText.string)
    Clipboard.getSystemClipboard().setContent(content)
}

class TableFold(val row: Int, val string: String)
a
oh no, I take it back
This is a very short solution, and an interesting one at that. It is a little overwhelming to look at at first, would you consider adding some comments to just talk about the steps? I only say this because it's doing a couple different things within a single
copyTable
function
I understand it now reading through it but I think it would be helpful for others that intend on looking at the code