Problem
One of the very basic needs when you deal with tables is to copy/paste data of table cells. The JavaFX TableView doesn\'t support it out of
After some digging and reading about solutions with reflection I found out myself that it's easier than I thought. And most important: Without reflection.
I thought I'd share the code, hope it'll be of help to others.
Here's the basic method to modify a cell. This is just what I found out. In case someone knows a better method, then please share it.
// get cell
TableColumn tableColumn = table.getColumns().get(colIndex);
ObservableValue observableValue = tableColumn.getCellObservableValue(rowIndex);
if( observableValue instanceof StringProperty) {
((StringProperty) observableValue).set(clipboardCellContent);
}
So the paste method basically looks like this:
public static void pasteClipboard( TableView<?> table) {
// abort if there's not cell selected to start with
if( table.getSelectionModel().getSelectedCells().size() == 0) {
return;
}
// get the cell position to start with
TablePosition pasteCellPosition = table.getSelectionModel().getSelectedCells().get(0);
System.out.println("Pasting into cell " + pasteCellPosition);
String pasteString = Clipboard.getSystemClipboard().getString();
System.out.println(pasteString);
int rowClipboard = -1;
StringTokenizer rowTokenizer = new StringTokenizer( pasteString, "\n");
while( rowTokenizer.hasMoreTokens()) {
rowClipboard++;
String rowString = rowTokenizer.nextToken();
StringTokenizer columnTokenizer = new StringTokenizer( rowString, "\t");
int colClipboard = -1;
while( columnTokenizer.hasMoreTokens()) {
colClipboard++;
// calculate the position in the table cell
int rowTable = pasteCellPosition.getRow() + rowClipboard;
int colTable = pasteCellPosition.getColumn() + colClipboard;
// skip if we reached the end of the table
if( rowTable >= table.getItems().size()) {
continue;
}
if( colTable >= table.getColumns().size()) {
continue;
}
String clipboardCellContent = columnTokenizer.nextToken();
// System.out.println( rowClipboard + "/" + colClipboard + ": " + cell);
// get cell
TableColumn tableColumn = table.getColumns().get(colTable);
ObservableValue observableValue = tableColumn.getCellObservableValue(rowTable);
System.out.println( rowTable + "/" + colTable + ": " +observableValue);
// TODO: handle double, etc
if( observableValue instanceof StringProperty) {
((StringProperty) observableValue).set(clipboardCellContent);
}
else if( observableValue instanceof IntegerProperty) {
int value;
try {
value = NumberFormat.getInstance().parse(clipboardCellContent).intValue();
((IntegerProperty) observableValue).set(value);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
}
}
You can get the full code on this gist.