Creating a new JTable from current JTable view
I am working on a project that involves JTable and performing sorting and filtering operations on it. I am done with the sorting and filtering part and now I want to be able to create a new table from the current view of older开发者_开发问答 table.
e.g. If I apply certain filters to my old table, some rows are filtered out. I don't want those filtered out rows in my new table. I figured that I can convert the new row indices to model indices and add the cell values manually to new table's model, but I was wondering if there's any other efficient way to do this? Following is what I ended up doing://this code block will print out the rows in current view
int newRowCount = table.getRowCount();
int newColumnCount = table.getColumnCount();
for (int i = 0; i < newRowCount; i++) {
for (int j = 0; j < newColumnCount; j++) {
int viewIndex = table.convertRowIndexToModel(i);
String value = (String) model.getValueAt(viewIndex, j);
System.out.print(value + "\t");
}
System.out.println();
}
no need for any index conversion, simply ask query the table instead of the underlying model
for (int i = 0; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
Object value = table.getValueAt(i, j);
System.out.print(value + "\t");
}
}
Note: better rename the i/j to row/column for readability, was too lazy ;-)
精彩评论