【问题标题】:Jtable cannot sort Integer or Double [closed]Jtable无法对整数或双精度进行排序[关闭]
【发布时间】:2016-02-07 18:35:22
【问题描述】:

我有一个 5 列的表(1-2-3 字符串 4 整数 5 双精度) 当我尝试按最后两列对表格进行排序时,它的排序不正确。

我尝试使用比较器,但我的表模型得到 IndexOutOfBoundsException

private String[] colonne  = {"Barcode", "Modello", "Descrizione", 
                                "Quantitativo", "prezzo"};

//other code

DefaultTableModel tableModel = new DefaultTableModel(colonne, 0);

//other code

table = new JTable(tableModel);

TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(tableModel);


sorter.setComparator(0, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2)
            {
                return Integer.parseInt(o1) - Integer.parseInt(o2);
            }
        });



table.setRowSorter(sorter);

我该如何解决这个问题?

【问题讨论】:

标签: java swing sorting jtable comparator


【解决方案1】:

如果您的列包含 Integer 和 Double 对象,那么您需要覆盖 TableModelgetColumnClass(...) 方法以告诉表格该列的类是什么:

@Overide
public Class getColumnClass(int column)
{
    if (column == 4)
        return Double.class;
    else if (column == 3)
        return Integer.class;
    else
        return String.class;
}

然后该表将使用适当的比较器。您无需创建自定义比较器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    相关资源
    最近更新 更多