AbstractDataTable fireTableDataChanged() does not refresh jtable

前端 未结 1 1783
不思量自难忘°
不思量自难忘° 2021-01-28 18:21

I am having difficulties while adding data to my jtable. It first loads the data from collection, with a jtextfield I add a new data, certainly data is added in collection debug

相关标签:
1条回答
  • 2021-01-28 18:50

    This method is not well implemented:

    public void insertData(String values) {
        vehicleService.createVehicleType(values);
        fireTableDataChanged(); // No, call fireTableRowsInserted(...) instead
        ...
    }
    

    Calling fireTableDateChanged() is excesive and unnecessary at this point since you seem to add a single row to your table. The correct implementation should call fireTableRowsInserted(int firstRow, int lastRow) as follows:

    public void insertData(String values) {
        vehicleService.createVehicleType(values);
        int lastIndex = vehicleService.retrieveVehicleTypes().size() - 1;
        fireTableRowsInserted(lastIndex, lastIndex); // first and last indices are the same
    }
    

    In addition there's no need to revalidate() nor repaint() nothing after adding new rows to the table model. Simply notifying the listeners is enough: the JTable is a listener of its own model and will repaint itself accordingly on TableModelEvents.

    0 讨论(0)
提交回复
热议问题