gpt4 book ai didi

java - 如何在 JTable 上设置自定义顺序

转载 作者:行者123 更新时间:2023-11-30 03:23:52 24 4
gpt4 key购买 nike

我有一个带有自定义 JTableModel 的 JTable,现在我想创建一个自定义比较器,以便用户可以使用我的自定义方法对所有列进行排序。

我有这个代码:

列监听器

public class ColumnListener extends MouseAdapter {
protected JTable table;

public ColumnListener(JTable t) {
table = t;
}

public void mouseClicked(MouseEvent e) {
TableColumnModel colModel = table.getColumnModel();
int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
int modelIndex = colModel.getColumn(columnModelIndex)
.getModelIndex();

if (modelIndex < 0)
return;
if (sortCol == modelIndex)
isSortAsc = !isSortAsc;
else
sortCol = modelIndex;

for (int i = 0; i < columnsCount; i++) {
TableColumn column = colModel.getColumn(i);
column.setHeaderValue(getColumnName(column.getModelIndex()));
}
table.getTableHeader().repaint();

Collections.sort(v,new MyComparator(isSortAsc,columnModelIndex));
table.tableChanged(new TableModelEvent(MyTableModelSpese.this));
table.repaint();
}
}

我的比较器

class MyComparator implements Comparator {
protected boolean isSortAsc;
protected Integer numeroColonna;
public MyComparator( boolean sortAsc,Integer numberColumn) {
isSortAsc = sortAsc;
numeroColonna = numberColumn;
}

public int compare(Object o1, Object o2) {
if (!(o1 instanceof NotaSpese) || !(o2 instanceof NotaSpese))
return 0;
NotaSpese s1 = (NotaSpese) o1;
NotaSpese s2 = (NotaSpese) o2;
int result = 0;

if(numeroColonna==1){
//ordinamento per data
result = s1.getDataOperazioneData().compareTo(s2.getDataOperazioneData());
}

if (!isSortAsc)
result = -result;
return result;
}

public boolean equals(Object obj) {
if (obj instanceof MyComparator) {
MyComparator compObj = (MyComparator) obj;
return compObj.isSortAsc == isSortAsc;
}
return false;
}
}

当我尝试订购一列时,数据(列==1)并且我在订购后看到了集合

Collections.sort(v,new MyComparator(isSortAsc,columnModelIndex));

集合v中对象的顺序是可以的。但是,如果我看到表中的元素不是按我的方法排序的。我看到这个数据

2015-01-31
2015-12-30
2014-12-28

如何修复它?

最佳答案

我认为如果您使用TableRowSorter,则可以避免使用自定义MouseAdapter

TableRowSorter tableRowSorter = new TableRowSorter(tableModel.getModel());
//add your comparator to every column you want. in this case column with index 1
tableRowSorter.setComparator(1, new MyComparator(false));
table.setRowSorter(tableRowSorter);

您还可以参数化您的比较器,这样您就不必转换为 NotaSpese

private class MyComparator implements Comparator<NotaSpese> {

protected boolean isSortAsc;

public MyComparator(boolean sortAsc) {
isSortAsc = sortAsc;
}

@Override
public int compare(NotaSpese o1, NotaSpese o2) {

int result = o1.getDataOperazioneData().compareTo(o2.getDataOperazioneData());

if (!isSortAsc) {
result = -result;
}
return result;
}
}

关于java - 如何在 JTable 上设置自定义顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30731005/

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