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

I am trying to sort my JTable by extending DefaultTableModel and overriding getColumnClass () as follows:

public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } 

It works fine if there is no NULL in this cell. So I changed it as follows:

  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 at least one cell in the column is not NULL. But if all the cells in the column are NULL, this does not work ('casue returns nullPointerException).

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

Hasan

+4
source share
5 answers

Select the default type. return String.class; is a completely safe solution.

-1
source

Do you know what type you expect each column to contain in front of you?

If so, you can build an array with class objects and simply return the corresponding one.

 Class[] columns = new Class[]{String.class, String.class, Date.class}; public Class getColumnClass(int c) { return columns[c]; } 
+6
source

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; } }; 
+3
source

It is very simple to solve this problem. Take a look at the code changes I made. This code has been tested without error.

 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(); } 
0
source
 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 problem with returning String.class if all cells in column NULL

-1
source

Source: https://habr.com/ru/post/1382515/


All Articles