나는 3 열로 JTable
을 가지고 있습니다. 각 열은 자체 형식이 테이블은 다음과 같다 : 정렬이 잘못된 것을 (당신이 볼 수있는)객체를 포함한 setAutoCreateRowSorter
문제는 (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;
}
}
아! 내 손에 실수. 너는 옳다. 고마워요! 지금 일하는 것 같다 :) – Grains