2013-07-01 3 views
1

나는 3 열로 JTable을 가지고 있습니다. 각 열은 자체 형식이 테이블은 다음과 같다 : 정렬이 잘못된 것을 (당신이 볼 수있는)객체를 포함한 setAutoCreateRowSorter

enter image description here

문제는 (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; 
    } 
} 

답변

2

는 거짓말을 getColumnClass 오버라이드 (override) 귀하 : 두 번째 열 유형 TablePercentValue이 아닌, 그것은 여전히 ​​String입니다. 귀하의 예제의 목적을 위해, 이것은 당신이 데이터를 채울 경우 고정 할 수 있습니다 다음 TablePercentValue 생성자 내부

for(int j=0; j<tableData[0].length; j++){ 
    if(j==2) 
     tableData[i][j] = new TablePercentValue(i+","+j+"%"); 
    else if(j == 1) 
     tableData[i][j] = i+":"+j; 
    else 
     tableData[i][j] = i+""+j; 
    tableData[i][j] = value; 
} 

을 나는 여분의 replace(",", ".")

compValue = Double.parseDouble(value.replace("%", "").replace(",", ".")); 

를 추가했다 그러나 이것은 단지 현지화 일이 될 수도 있습니다 너를 위해 잘 달려라.

+0

아! 내 손에 실수. 너는 옳다. 고마워요! 지금 일하는 것 같다 :) – Grains