java 达人,
比如我自定义了一个 tablemodel,
class TModel
extends AbstractTableModel {
Object col[] = null;
Object[][] data = null;
public void setCollen(Object[] col) {
this.col = col;
}
public void setObj(Object[][] oo) {
this.data = oo;
}
public int getColumnCount() {
return col.length;
}
public int getRowCount() {
return data.length;
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public String getColumnName(int column) {
return (String) col[column];
}
public Class getColumnClass(int c) {
// return getValueAt(0,c).getClass();
Class outclass = null;
ImageIcon b = new ImageIcon();
if( c == 0 )
{
outclass = b.getClass();
}
else
{
outclass = super.getColumnClass(c);
}
return outclass;
}
public boolean isCellEditable(int row, int col) {
return false;
}
public void setValueAt(Object aValue, int row, int column) {
data[row][column] = aValue;
}
public void clear() {
data = null;
}
}
然后定义了一个 table,
TModel tableModel = new TModel();
JTable table = new JTable(tableModel);
现在想要使用 table.setRowSorter 对 table 排序,应该怎么写呢?
table.setRowSorter(new TableRowSorter(tableModel));
这样写好像不对呀。
达人能给个例子么?
------最佳解决方案--------------------------------------------------------
在TModel重写hasCode()和equals方法。
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(col);
result = prime * result + Arrays.hashCode(data);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TModel other = (TModel) obj;
if (!Arrays.equals(col, other.col))
return false;
if (!Arrays.equals(data, other.data))
return false;
return true;
}
定义你要排序的规则
------其他解决方案--------------------------------------------------------