Java FX table column sorting with Comparator does not work

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 22:01:52

Your problem can be solved by using a CellFactory for the column displaying Kundenwert. This way you don't need the kundenwertFormatted field in your model, since formatting will be done by the cell factory:

public class KundenwertCellFactory implements Callback<TableColumn<ProfilZuordnungTableRowModel, Double>, TableCell<ProfilZuordnungTableRowModel, Double>> {

    public TableCell<ProfilZuordnungTableRowModel, Double> call(TableColumn<ProfilZuordnungTableRowModel, Double> param) {
        TableCell<ProfilZuordnungTableRowModel, Double> cell = new TableCell<ProfilZuordnungTableRowModel, Double>() {

            @Override
            public void updateItem(final Double item, boolean empty) {
                if (item != null) {
                    setText(item.toString()); // you can format your value here
                }
            }
        };
        return cell;
    }
}

Then, you can create your comparator to compare kundenwert which is double:

public class KundenwerComparator implements Comparator<Double> {

    public int compare(Double o1, Double o2) {
        return o1 < o2 ? -1 : o1 == o2 ? 0 : 1;

    }

}

Finally, you can setup your column as follows:

TableColumn<ProfilZuordnungTableRowModel, Double> kundenwertColumn = new TableColumn<ProfilZuordnungTableRowModel, Double>();
kundenwertColumn.setText("Kundenwert");

kundenwertColumn.setCellValueFactory(new PropertyValueFactory<ProfilZuordnungTableRowModel, Double>("kundenwert"));
kundenwertColumn.setComparator(new KundenwerComparator());
kundenwertColumn.setCellFactory(new KundenwertCellFactory());

Note that I used type arguments since TableColumn (and it's companions) is generic.

Your comparator for kundenwertColumn should implement a Comparator for Strings. It goes like

class KundenwertFormattedComparator implements Comparator<String> {
    @Override
    public int compare(String t, String t1) {
         return getKundenwertFromFormatted(t) < getKundenwertFromFormatted(t1)  ? -1 : getKundenwertFromFormatted(t) == getKundenwertFromFormatted(t1) ? 0 : 1;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!