Hi All,
I have a JTable which displays different objects in different rows. I am trying to implement the copy paste function so that the user can do CTRL+C and paste the data in an excel spread sheet. Initially I implemented the toString method for all the objects that the table displays. But, I had to modify the copy functionality, so that, for each table row, 2 excel rows can be generated. This is how I do it.
private StringBuilder getTableData(){
StringBuilder sb = new StringBuilder();
int columns = table.getColumnCount();
int rows = table.getRowCount();
StringBuilder row1 = null;
StringBuilder row2 = null;
Object value = null;
for(int i = 0; i < rows; i++) {
row1 = new StringBuilder();
row2 = new StringBuilder();
for(int j = 0; j < columns; j++) {
if(table.getModel().getValueAt(i, j) != null){
value = table.getModel().getValueAt(i, j);
if(value instanceof FieldComparison){
row1.append(((FieldComparison)value).getField1());
row2.append(((FieldComparison)value).getField2());
} else {
row1.append(value.toString());
row2.append(value.toString());
}
}
if(j < (columns - 1)){
row1.append("\t");
row2.append("\t");
}
}
if(i < (rows - 1)){
row1.append("\n");
row2.append("\n");
//sb.append("\n");
}
sb.append(row1);
sb.append(row2);
}
return sb;
}
I copy this data to the clipboard as follows:
StringBuilder sb = getTableData();
StringSelection allData = new StringSelection(sb.toString());
cb.setContents(allData, allData);
try {
Transferable content = cb.getContents(null);
String clipBoardContents = (String)content.getTransferData(DataFlavor.stringFlavor);
System.out.println(clipBoardContents);
}catch(Exception e){
System.out.println("Transfer data error " + e.toString());
}
At this point I can see the proper data in the console, However when I try to do a CTRL+V on the excel spreadsheet, the data appears as if the toString method was called on each object. It appears like the clipboard data that I added has been overridden somehow. Not sure what the problem is. Please Help!
Thanks!