简体   繁体   中英

JTable sorting double wrong

I'm trying to sort a column of doubles in a JTable. I was managed to sort it but it seems the sorter doesn't considerate minus.

This is the table code:

    table = new JTable(new DefaultTableModel(new Object[]{"קניה", "מכירה", "שם"}, 0));
    table.setCellSelectionEnabled(true);
    table.setAutoCreateRowSorter(true);
    table.getTableHeader().setReorderingAllowed(false);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    table.getColumnModel().getColumn(0).setPreferredWidth(80); 
    DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)table.getDefaultRenderer(Object.class);
    renderer.setHorizontalAlignment(JLabel.RIGHT);        
    jPanel.add(new JScrollPane(table), BorderLayout.CENTER);
    frmYadAd.getContentPane().add(jPanel);   

This is the outcome:

Image

Implementing your own TableModel will give you control over sorting.

By default, the JTable sorts a column by comparing String values returned from row objects of that column. Therefore, if the table contains a column that stores only integer numbers, then default sorting behavior is comparing String values instead of number values, which is wrong.

If we @Override the getColumnClass() method to return the class type of each column in the table, then the table knows the exact type of the column in advance to implement correct sorting behavior for that column.

See a simple tutorial with examples http://www.codejava.net/java-se/swing/6-techniques-for-sorting-jtable-you-should-know .

create class table model extends AbstractTableModel and overide method getColumnClass return Double.class for your column.

that example: http://www.java2s.com/Code/Java/Swing-JFC/CreatingsimpleJTableusingAbstractTableModel.htm

The default row sort is only for String. If you use another Objects, these object will be transfer to String and then compare, for example Double, it will be tranfer to Double.toString(). Therefore, to compare Other object rather than string, it is better to write a comparator and set it into table, below some codes about sort double column:

   TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>    (table.getModel());
    int double_Column = 1;
    sorter.setComparator(double_Column, new Comparator<Double>(){
        public int compare(Double o1, Double o2){
            return o1.compareTo(o2);
        }

    });
    table.setRowSorter(sorter);
 YourTable.setAutoCreateRowSorter(true);

it's sorting the columns by click on one of them, it'll sort the other. as simple as that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM