1

JTable3列あります。各列には独自の形式があり、テーブルは次のようになります。

ここに画像の説明を入力

問題は (ご覧のとおり) 並べ替えが正しくないことです ( 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;
    }
}
4

1 に答える 1

3

あなたのオーバーライドgetColumnClassは嘘をついています: 2 番目の列は typeTablePercentValueではなく、まだString. 例の目的のために、これはデータを入力する場所で修正できます。

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;
}

コンストラクター内でTablePercentValue、余分なものを追加する必要がありましたreplace(",", ".")

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

しかし、これは単なるローカリゼーションであり、問​​題なく動作する可能性があります。

于 2013-07-01T15:22:43.410 に答える