Java JTable排序不适用于仅一列 [英] Java JTable Sorting Doesn't Work for Just One Column

查看:49
本文介绍了Java JTable排序不适用于仅一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java Swing应用程序(内置于Netbeans 6.9中)中,我有一个包含21列的JTable.这些列中约有14个包含双精度值.前6列是日期和字符串.在第七列,双打开始.当应用运行时,通过单击表的标题行,表中的每一列都会正确排序-第7列除外.该表认为该数据为字符串类型,并将其排序为字符串.

In a Java Swing app (built in Netbeans 6.9), I have a JTable with 21 columns. About 14 of those columns consist of double values. The first 6 columns are dates and strings. At the 7th column, doubles start. Every column in the table will sort correctly by clicking on the header row of the table when the app is running -- except the 7th column. The table thinks this data is of type string and it sorts it as a string.

如果我将数据移到另一列,则该新列现在将按字符串排序.因此,问题不在于特定的列,而是有关此数据的事情.

If I move the data to another column, that new column now sorts as a string. So the problem is not the particular column, but something about this data.

但是,数据定义为双重,纯净和简单的:

However, the data is defined as a double, pure and simple:

double x;
public double getX() {
    return x;
}

可以正确排序的双精度列以相同的方式定义.

The columns of doubles that do sort correctly are defined the same way.

我什至尝试将有问题的数据转换为双精度数据(即使已经是双精度数据),并且没有任何区别.

I even tried casting this problematic data to a double (even though it is already a double) and it didn't make any difference.

我还尝试为不会按数字排序的列设置单元格渲染器(即使另一列不需要此步骤).

I also tried setting a cell renderer for the column that won't sort as a number (even though the other column don't need this step).

table.getColumnModel().getColumn(6).setCellRenderer(table.getDefaultRenderer(Double.class));

还有什么可能导致此数字列按字符串排序?

What else could be causing this column of numbers to sort as strings?

推荐答案

我必须在扩展DefaultTableModel的类中实现getColumnClass.

I had to implement getColumnClass in my class that extends DefaultTableModel.

public class MyTableModel extends DefaultTableModel {

    public MyTableModel(Object[][] data, Object[] columnNames) {
        super(data, columnNames);
    }
            @Override
    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }
}

这篇关于Java JTable排序不适用于仅一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆