I am using JTable with an empty row at the bottom of the table in order to give the ability of adding new line to the table.
After insert or writing data in the empt
I gave this a try, and I think I found a solution.
Instead of creating that empty row in the TableModel, I fake it in the JTable, and only create it when the user actually enters some data.
The RowSorter only sorts rows of the TableModel, so our row is not affected and remains as the last row.
public class NewLineTable extends JTable {
@Override
public int getRowCount() {
// fake an additional row
return super.getRowCount() + 1;
}
@Override
public Object getValueAt(int row, int column) {
if(row < super.getRowCount()) {
return super.getValueAt(row, column);
}
return ""; // value to display in new line
}
@Override
public int convertRowIndexToModel(int viewRowIndex) {
if(viewRowIndex < super.getRowCount()) {
return super.convertRowIndexToModel(viewRowIndex);
}
return super.getRowCount(); // can't convert our faked row
}
@Override
public void setValueAt(Object aValue, int row, int column) {
if(row < super.getRowCount()) {
super.setValueAt(aValue, row, column);
}
else {
Object[] rowData = new Object[getColumnCount()];
Arrays.fill(rowData, "");
rowData[convertColumnIndexToModel(column)] = aValue;
// That's where we insert the new row.
// Change this to work with your model.
((DefaultTableModel)getModel()).addRow(rowData);
}
}
}