gpt4 book ai didi

java - JTable 中的日期排序无效

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:50:37 24 4
gpt4 key购买 nike

请看下面的代码

import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.*;

public class TableBasic extends JFrame
{
public TableBasic()
{

String[] columnNames = {"Date", "String", "Long", "Boolean"};
Object[][] data =
{
{getJavaDate("13-11-2020"), "A", new Long(1), Boolean.TRUE },
{getJavaDate("13-11-2018"), "B", new Long(2), Boolean.FALSE},
{getJavaDate("12-11-2015"), "C", new Long(9), Boolean.TRUE },
{getJavaDate("12-11-2015"), "D", new Long(4), Boolean.FALSE}
};

final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.setAutoCreateRowSorter(true);
table.getColumnModel().getColumn(0).setCellRenderer(tableCellRenderer);

// DefaultRowSorter has the sort() method
DefaultRowSorter sorter = ((DefaultRowSorter)table.getRowSorter());
ArrayList list = new ArrayList();
list.add( new RowSorter.SortKey(0, SortOrder.DESCENDING) );
sorter.setSortKeys(list);
sorter.sort();

JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
}

private TableCellRenderer tableCellRenderer = new DefaultTableCellRenderer()
{

SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy");

public Component getTableCellRendererComponent(JTable table,Object value, boolean isSelected, boolean hasFocus,int row, int column)
{
if( value instanceof Date)
{
value = f.format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected,hasFocus, row, column);
}
};

private Date getJavaDate(String s)
{
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date d = sdf.parse(s);
return d;

} catch (ParseException ex) {
Logger.getLogger(TableBasic.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}



public static void main(String[] args)
{
TableBasic frame = new TableBasic();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}

现在,只需尝试使用 Date 字段对其进行排序。它以无效的方式对其进行排序!下面是结果!

enter image description here

为什么会这样?我什至用过 cell render!

最佳答案

表格不知道该列总是包含 Date 实例,因此它必须按时间顺序排序,除非您通过覆盖表格模型的 getColumnClass() 方法给它该信息:

final Class<?>[] columnClasses = new Class<?>[] {Date.class, String.class, Long.class, Boolean.class};

DefaultTableModel model = new DefaultTableModel(...) {
@Override
public Class<?> getColumnClass(int column) {
return columnClasses[column];
}
});
JTable table = new JTable(model);

额外的好处:数字和 boolean 列将自动呈现并正确排序。

关于java - JTable 中的日期排序无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26924799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com