Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with JTable sorting of integer values

Currently I have a JTable that uses RowSorter, but when I click the header that I want it to sort in, it displays the rows in a weird order

  • 1
  • 10
  • 11
  • ...
  • 2
  • 20
  • 21
  • ...
  • 3
  • 30

Yet when I select a certain row, say row 5, it changes the row that's labeled 5. Any reason as to why this is happening and how I can fix it?

like image 719
Thomas Avatar asked Mar 10 '26 07:03

Thomas


2 Answers

You can set the column type for a JTable by setting its model explicitly like in the following example

setModel(new DefaultTableModel(new Object[0][], new String[] {
                "SELECT", "WHERE", "FIELD", "TYPE" }) {
            Class[] types = { Boolean.class, Boolean.class, String.class,
                    String.class };
            boolean[] canEdit = { true, false, false, false };

            @Override
            public Class getColumnClass(int columnIndex) {
                return this.types[columnIndex];
            }

            public boolean isCellEditable(int columnIndex) {
                return this.canEdit[columnIndex];
            }
        });

Give your column classes like this (here column one and two are Boolean and the rest String.

 Class[] types = { Boolean.class, Boolean.class, String.class,String.class };
like image 110
prajeesh kumar Avatar answered Mar 11 '26 21:03

prajeesh kumar


You're treating the row contents as text. Your sort order is alphabetical rather than numerical. If you treat the contents as numbers it should work itself out.

like image 43
Amos M. Carpenter Avatar answered Mar 11 '26 19:03

Amos M. Carpenter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!