Question

i'm trying to make my JTable show changes made to my TableModel extending AbstractTableModel. I made a Heap to insert all the documents and then I apply a heapSort on my heap array, so this ordered array should be my TableModel data. It looks like this:

public class ModeloTabla extends AbstractTableModel {

    private Heap heap;
    private Nodo[] datos;

    @Override
    public int getRowCount() {
        return heap.getNumNodos();
    }

    @Override
    public int getColumnCount() {
        return 4;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if ( !heap.empty() ) {
            datos = heap.heapSort();
        }
        Documento doc = datos[rowIndex].getDocumento();
        switch ( columnIndex ) {
            case 0:
                return doc.getNombre();
            case 1:
                return doc.getHojas();
            case 2:
                return doc.getPrioridad();
            default:
                return null;
        }
    }
}

Inside the getValueAt method when I call heap.heapSort() the heap internal array is destroyed and it returns a Nodo[] with the ordered nodes. So when datos has an ordered array with nodes, my JTable won't show the data. Now, if I don't execute the heap.heapSort() and instead just call for the unordered array from the heap, my JTable shows everything.

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
        datos = heap.getDatos();
        Documento doc = datos[rowIndex].getDocumento();
        ... //This works but datos is unordered
    }
}

I've tried replacing the Heap unordered array with the ordered one inside heapSort() and returning it using getDatos() but then the JTable again won't show up, also I've checked for the returning array from heapSort() and it's working well, the data is the same as the one from getDatos() but ordered. Any help with this would be very appreciated, thanks.

Was it helpful?

Solution

In the getValueAt() method you are retrieving the data from the datos object.

Documento doc = datos[rowIndex].getDocumento();

So the row count should be based on the number of rows in the datos object.

public int getRowCount() {
        //return heap.getNumNodos();
        return datos.length;
    }

The getValueAt() method should NOT be sorting the data. The data in the model should already be sorted. Either sort it externally or sort it when you create the model. That is the getValueAt() method should not be changing the structure of the data. Also every time you change the data you would need to resort.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top