我无法对JTable进行排序 - Jave

时间:2017-11-12 17:46:54

标签: java swing sorting jtable

单击列时,排序结果错误:

The sorted results

这是我的代码:

DefaultTableModel tableModel = new DefaultTableModel(data, columns) {

        @Override
        public boolean isCellEditable(int row, int column) {
            //all cells false
            return false;
        }
    };
    JTable table = new JTable();
    table.setModel(tableModel);

    //Sort table
    table.setAutoCreateRowSorter(true);

以下是列和数据的代码:
couponArray:它是对象

        // Columns of table
    String[] columns = {"Name of Coupon Provider", "Name of product", "Price of product",
            "Discount rate of the coupon (%)", "Final price", "Expiration Period", "Status of a coupon"};

    //Data of table
    int lengthArray = couponArray.size();
    String data[][] = new String [lengthArray][7];
    for (int i = 0; i < lengthArray; i++){
        Coupon sTmp = (Coupon)couponArray.get(i);
        data[i][0] = sTmp.getNameOfCouponProvider();
        data[i][1] = sTmp.getNameOfProduct();
        data[i][2] = Double.toString(sTmp.getPriceOfProduct());
        data[i][3] = Integer.toString(sTmp.getDiscountRateOfCoupon());

        //Get final price
        double finalPrice = sTmp.getPriceOfProduct() -
                sTmp.getPriceOfProduct()*((double)sTmp.getDiscountRateOfCoupon()/100);
        data[i][4] = new Formatter().format("%.2f", finalPrice).toString();
        data[i][5] = Integer.toString(sTmp.getExpirationPeriod());
        data[i][6] = sTmp.getStatusOfCoupon();
    }

1 个答案:

答案 0 :(得分:0)

请参阅下面的解决方案。现在它排序&#34;产品价格&#34;正确。主要更改是覆盖表模型中的getColumnClass()。随着这一变化,&#34;产品价格&#34;值被视为数字。早些时候,他们被视为字符串。

我还将数据类型的类型更改为Object [] []。并将double值设置为data [i] [2]而不将其转换为String。

const data = [{"name,age,address": "asd,20,\"12/76, 11th cross\""},{"name,age,address": "dff,30,\"33, 11th cross\""},{"name,age,address": "f,22,\"7g/22, 12th cross\""},{"name,age,address": "ghth,55,\"4h, 13th cross\""}];
var result = data.reduce((res, obj) => {
  let [name, age, ...address] = obj["name,age,address"].split(',');
  res.name.push(name);
  res.age.push(age);
  res.address.push(address.join(''));
  return res;
},{name:[],age:[],address:[]});
console.log(result);