0

I have a program that reads a CSV file (it's a table) using BufferedReader which stores it in ArrayList. The column I want to sort according to is an integer value and i want to do it in ascending order. The column I want to use is column 2. I want the column to be sorted as soon as I open the jtable. I have tried using TableRowSorter but I want the table to automatically sort. Is there any other way of doing it. I have used AbstractTableModel maybe I can input a code there.

Class MyModel extends AbstractTableModel {

    private final String[] columnNames = { "Studentname" "Age" "Id"}
    private Class[] columnClass = { String.class, Integer.class, Integer.class };
    private ArrayList<String[]> Data = new ArrayList<String[]>();

    public void AddCSVData(ArrayList<String[]> DataIn) {
        this.Data = DataIn;            
        this.fireTableDataChanged();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;// length;
    }    

    @Override
    public int getRowCount() {
        return Data.size();
    }

    @Override
    public String getColumnName(int col) {
       return columnNames[col];
    }

    public void setValueAt(Object aValue, int row, int col) {
        Data.get(row)[col] = (String) aValue;
    }

    @Override
    public Object getValueAt(int row, int col) {          
      return Data.get(row)[col];
    }
}
Mort
  • 3,379
  • 1
  • 25
  • 40
hello007
  • 29
  • 1
  • 8
  • `"I have tried using TableRowSorter but i want the table to automatically sort."` -- this is in fact how you have the JTable "automatically" sorted. – Hovercraft Full Of Eels Mar 30 '17 at 16:05
  • Many problems with the code: 1) Variable names should NOT start with an upper case character. 2) You want to sort on an Integer value, but you never implement the `getColumnClass(...)` method so all data will be treated as a String. 3) Your data structure hold an Array of Strings. It should be an Array of Objects if you want to add Integers. 4) the `setValueAt(...)` method is implemented incorrectly since you don't invoke the correct fireXXX(...) method. There is no need for a completely custom model, just extend the `DefaultTableModel` and override the `getColumnClass()` method.. – camickr Mar 30 '17 at 17:08

0 Answers0