0
votes

I'm trying to read a csv file and get it setup to convert into another format to save some time at work, but the JTable i'm loading it into throws an exception when a row has a length less than the expected column. Is there a method to create an empty cell if row length < column length?

here is the table model:

   private class CSVTableModel extends AbstractTableModel{

   private ArrayList<String[]> list;
   private String[] columns;

   public CSVTableModel() {
       this.list = p.getData();
       this.columns = p.getHeaders();
   }

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

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

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

   @Override
   public Object getValueAt(int row, int col) {
       return list.get(row)[col];
   }

   @Override
   public void setValueAt(Object value, int row, int col)  {
       list.get(row)[col] = (String) value;
       this.fireTableCellUpdated(row, col);
   }
   }

So you can see with the getValueAt(int row, int col) method it will cause an error if the col exceeds the String[].length.

1
"Is there a method to create an empty cell if row length < column length?" -- yes, you code this yourself. Add some null values if this happens. - Hovercraft Full Of Eels

1 Answers

0
votes

I literally solved it after posting. Rubber duck debugging.

@Override
   public Object getValueAt(int row, int col) {
       if ( col < list.get(row).length )   {
            return list.get(row)[col];
       }    else    {
           return "";
       }
   }

added a condition and works fine now. Should've seen it before.