我有一个JTable
3 列。每列都有自己的格式,表格如下所示:
问题是(如您所见)排序不正确(setAutoCreateRowSorter
)。
我试图为此定义我自己的对象类型col3
,implements Comparable
并toString()
为此对象提供了一个方法。但这似乎并不能帮助我正确排序。
知道我做错了什么吗?
public class SortJTable {
public static void main(String[] args) {
String[] columns = getTableColumns();
Object[][] tableData = getTableValues();
TableModel model = new DefaultTableModel(tableData, columns) {
@Override
public Class getColumnClass(int col) {
if (col == 2) // third column is a TablePercentValue
return TablePercentValue.class;
else
return String.class;
}
};
JTable table = new JTable(model);
table.setAutoCreateRowSorter(true); // Make it possible to column-sort
JFrame frame = new JFrame();
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
}
private static String[] getTableColumns(){
String[] columns = new String[3];
columns[0] = "col1";
columns[1] = "col2";
columns[2] = "col3";
return columns;
}
private static Object[][] getTableValues(){
Object[][] tableData = new Object[100][3];
for(int i=0; i<tableData.length; i++){
for(int j=0; j<tableData[0].length; j++){
String value;
if(j==2)
value = i+","+j+"%";
else if(j == 1)
value = i+":"+j;
else
value = i+""+j;
tableData[i][j] = value;
}
}
return tableData;
}
}
class TablePercentValue implements Comparable<TablePercentValue> {
private String value;
private double compValue;
public TablePercentValue(String value){
this.value = value;
// Remove "%"-sign and convert to double value
compValue = Double.parseDouble(value.replace("%", ""));
}
public String toString(){
return value;
}
@Override
public int compareTo(TablePercentValue o) {
return compValue>o.compValue ? 1 : -1;
}
}