1

I have a simple JTable with 3 columns. The numbers get big so I format them by putting commas in them, i.e. 100,000. However, in doing so, my table sort does not work.

How can I fix this?

package tables;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class mainwindow extends JPanel {

 public static void main(String[] args) {
        Object[][] data = {
            {"75,500", "Don't Let Go", new Integer(179)},
            {"121,343", "Photograph", new Integer(29)},
            {"32,323", "Hash Pipe", new Integer(186)}
        };
        Object[] columns = {"Track #", "Title", "Length"};
        DefaultTableModel model = new DefaultTableModel(data,columns) {
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    default:
                        return String.class;
                }
            }
        };
        JTable table = new JTable(model);
        JScrollPane scroll = new JScrollPane(table);
        table.setAutoCreateRowSorter(true);
        JOptionPane.showMessageDialog(null, scroll);
    }
}

Screenshot of my application

aterai
  • 9,658
  • 4
  • 35
  • 44

1 Answers1

3

You will not get a numeric sort for the first column simply because the data are String and not numeric, I would suggest you keep your data as Integer,

   Object[][] data = {
        {75500, "Don't Let Go", new Integer(179)},
        {121343, "Photograph", new Integer(29)},
        {32323, "Hash Pipe", new Integer(186)}
    };

Create and use a new cellRender with the format you want:

  table.setDefaultRenderer(Integer.class, new DefaultTableCellRenderer() {
     private NumberFormat numberFormat = new DecimalFormat("#,###,###");
     @Override
     protected void setValue(Object aValue) {
        Integer value = (Integer) aValue;
        super.setValue(numberFormat.format(value));
     }
  });
Mooolo
  • 428
  • 2
  • 7
  • 1+ for overriding the `setValue(...)` method of the renderer. – camickr Nov 30 '14 at 19:26
  • Note that this procedure might lead to the numbers not being aligned to the right of the cell anymore. To fix this, simply use renderer.setHorizontalAlignment(JLabel.RIGHT). See [this related question](https://stackoverflow.com/questions/3467052/set-right-alignment-in-jtable-column). – Candamir Jul 25 '17 at 17:43