0

By default, it's sorting by the first column ascending and it's ok. The problem comes when I try to order the last two columns clicking the headers (Integer.class and Float.class). These columns have Integers and Floats with 3 and 4 digits. It sorts the integers/floats with 4 digits first and then the numbers with 3 digits (ascending) or upside down if I sort descending. The first three columns are Strings and they are well sorted. I would like to order either ascending or descending independently of the number of digits.

This is the code:

    tablePlanes = new JTable();
    JTableHeader cabecera = tablePlanes.getTableHeader();
    tablePlanes.setModel(new DefaultTableModel(new Object[][] {},
            new String[] { "Titulación", "Universidad", "Comunidad", "Precio", "Nota de corte" }) {

        private static final long serialVersionUID = 1L;
        Class[] columnTypes = new Class[] { String.class, String.class, String.class, Integer.class, Float.class };

        public Class getColumnClass(int columnIndex) {
            return columnTypes[columnIndex];
        }
    });
    DefaultTableCellRenderer modelocentrar = new DefaultTableCellRenderer();
    ((DefaultTableCellRenderer) cabecera.getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
    modelocentrar.setHorizontalAlignment(SwingConstants.CENTER);
    tablePlanes.getColumnModel().getColumn(0).setCellRenderer(modelocentrar);
    tablePlanes.getColumnModel().getColumn(1).setCellRenderer(modelocentrar);
    tablePlanes.getColumnModel().getColumn(2).setCellRenderer(modelocentrar);
    tablePlanes.getColumnModel().getColumn(3).setCellRenderer(modelocentrar);
    tablePlanes.getColumnModel().getColumn(4).setCellRenderer(modelocentrar);
    tablePlanes.setAutoCreateRowSorter(true);
    tablePlanes.getRowSorter().setSortKeys(Arrays.asList(new RowSorter.SortKey(0, SortOrder.ASCENDING)));

I also attach two snapshots of the Application. Sorting descending Sorting ascending

Thank you so much in advance!

  • 4
    It _looks_ like your `TableModel` contains strings, but a [mcve] would make it clear. – trashgod May 18 '20 at 21:05
  • 1
    The [edit] 5 hours ago did not include a [mre] as suggested 16 hours ago by @trashgod. Have you solved it? If not, please post the MRE. – Andrew Thompson May 19 '20 at 13:56
  • 1
    Use `Integer.valueOf()` to add `Integer` values to your model, as shown [here](https://stackoverflow.com/a/4553842/230513), or `Float.valueOf()` for values of type `Float.class`. – trashgod May 19 '20 at 16:48

0 Answers0