Hasan
Hasan

Reputation: 309

JTable + getColumnClass() returns null if a cell contains NULL

I'm trying to sort my JTable by extending DefaultTableModel and overrriding getColumnClass() as follows:

 public Class getColumnClass(int c) {     

  return getValueAt(0, c).getClass();
}

It works perfectly fine if there is no NULL in that table cell. So I modified it in following way:

  public Class getColumnClass(int c) {


  for(int rowIndex = 0; rowIndex < data.size(); rowIndex++){

    Object[] row = data.get(rowIndex);

    if (row[c] != null) {
        return getValueAt(rowIndex, c).getClass();
    }
  }
  return getValueAt(0, c).getClass();
 }

Now, again, it works fine if there is atleast one cell in the column which is not NULL. But if all of the cells in the column is NULL, it doesn't work ('casue it returns nullPointerException).

Please ............help.... thanks in advance

Hasan

Upvotes: 4

Views: 13512

Answers (5)

jordao Manguena
jordao Manguena

Reputation: 1

It is extremely simple to solve this problem. Look at the code changes i made. This code was tested and is error free

public Class getColumnClass(int c) {  
  int columnCount;
  // dataModel is an object of the data Model class(default or abstract)
  columnCount=dataModel.getRowCount();
    if(columnCount<=1){
       return String.class;
    }
    return getValueAt(0, c).getClass();
}

Upvotes: 0

Hasan
Hasan

Reputation: 309

public Class getColumnClass(int c) 
    {     
    for(int rowIndex = 0; rowIndex < data.size(); rowIndex++)
    {
        Object[] row = data.get(rowIndex);
        if (row[c] != null) {
            return getValueAt(rowIndex, c).getClass();
        }   
    }
    return String.class;
}

Fixed the problem by return String.class if all cells in the column is NULL

Upvotes: -1

camickr
camickr

Reputation: 324098

This is the general code I use:

    JTable table = new JTable(data, columnNames)
    {
        public Class getColumnClass(int column)
        {
            for (int row = 0; row < getRowCount(); row++)
            {
                Object o = getValueAt(row, column);

                if (o != null)
                {
                    return o.getClass();
                }
            }

            return Object.class;
        }
    };

Upvotes: 3

execc
execc

Reputation: 1113

Pick 'default' type. return String.class; is quite safe solution.

Upvotes: 0

Eric Rosenberg
Eric Rosenberg

Reputation: 1533

Do you know what type you expect each column to contain before hand?

If so then you can build an array with the class objects and just return the appropriate one.

Class[] columns = new Class[]{String.class, String.class, Date.class};

public Class getColumnClass(int c) {  
     return columns[c];
}

Upvotes: 6

Related Questions