简体   繁体   English

JTable按日期排序

[英]JTable sort by date

I have a JTable with two columns, fileName and date modified . 我有一个JTable有两列, fileNamedate修改 I have added name String for the first column and added new Date(tempFile.lastModified()) for the second dateTime column. 我为第一列添加了名称字符串 ,为第二个dateTime列添加了new Date(tempFile.lastModified())

I rendered the dateTime column as a new SimpleDateFormat("MM/dd/yy HH:mm:ss") String. 我将dateTime列呈现为new SimpleDateFormat("MM/dd/yy HH:mm:ss")字符串。

I also enabled the m_listTbl.setAutoCreateRowSorter(true); 我还启用了m_listTbl.setAutoCreateRowSorter(true);

But the sort result in the date modified column is not right. 但是日期修改列中的排序结果不正确。

在此处输入图片说明

Why is this? 为什么是这样? Do I still need to write my own sorter? 我还需要编写自己的分类器吗?

EDIT: 编辑:

After commented out almost all extra code and not rendered by date String, I got the following result. 在注释掉几乎所有额外的代码并且未使用date String呈现之后,我得到了以下结果。 It seems in JTable Java sort Date object by day by default. 它似乎在默认按 JTable中的Java排序Date对象。 I will test more to see what's wrong with my code. 我将进行更多测试,以查看我的代码有什么问题。 在此处输入图片说明

EDIT2 EDIT2

I have tested and figured out. 我已经测试并找到答案。 If you use DefaultTableModel without overriding its getColumnClass() method, you will have trouble with Date or Number columns. 如果使用DefaultTableModel而不覆盖其getColumnClass()方法,则Date或Number列将遇到麻烦。

EDIT2 : Absolutely. 编辑2:绝对。 Having the same problem in a jtable linked to a tablemodel I can confirm that the problem is due to the class associated to the column value (EDIT2) in the tableModel . 在链接到tablemodel的jtable中有相同的问题,我可以确认问题是由于与tableModel的列值(EDIT2)关联的类tableModel Surprise was that Date column was of class Object no matter a perfect type Date was returned in my subclass of DefaultTableModel when overriding public Object getValueAt(int row, int col) . 令人惊讶的是,当重写public Object getValueAt(int row, int col)时,无论在我的DefaultTableModel子类中是否返回完美的Date类型,Date列都是Object类的。

Workaround is to override getColumnClass in your subclass of DefaultTableModel . 解决方法是在DefaultTableModel的子类中重写getColumnClass If you don't do that, sorting is done on Object for Dates with strange results when you sort the Date column. 如果不这样做,则在对“日期”列进行排序时,将对“日期对象”进行排序,结果会很奇怪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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