G
Ooh. TableRowSorter method https://docs.oracle.com/javase/8/docs/api/javax/swing/DefaultRowSorter.html#setComparator-int-java.util.Comparator- which allows a comparison of the values in the column. If you make it through the mass, there's something like that: // отмазка: я знаю, что хранить деньги, как число с плавающей точкой - плохо,
// но в примере сойдет.
Object[][] rowData = {
{ "строка 1", new Object[] {100.50d, "руб"} },
{ "строка 2", new Object[] {5d, "$"} },
{ "строка 3", new Object[] {89.99d, "\u20A4"} },
{ "строка 4", new Object[] {-8d, "$"} },
{ "строка 5", new Object[] {1000d, "$"} },
{ "строка 6", new Object[] {1d, "руб"} },
};
Object[] columnNames = { "caption", "currency" };
DefaultTableModel model = new DefaultTableModel( rowData, columnNames );
JTable table = new JTable( model );
table.getColumnModel().getColumn( 1 ).setCellRenderer( new CurrencyRenderer() );
TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>( model );
// реализация компаратора
sorter.setComparator( 1, new Comparator<Object>() {
@Override
public int compare( Object o1, Object o2 ) {
Object[] record1 = (Object[])o1;
Object[] record2 = (Object[])o2;
// сначала сравниваются валюты (как строки)
int result = ((String)record1[1]).compareTo( (String)record2[1] );
// если валюты одинаковые, то значения сумм (как Double)
return result != 0 ? result : ((Double)record1[0]).compareTo( (Double)record2[0]);
}
});
table.setRowSorter( sorter );
The work with the mass is causing horror and accent. It's worth thinking about making money in a separate class:public static class Money {
String currency;
Double value;
public Money( Double value, String currency ) {
this.value = value;
this.currency = currency;
}
public String currency() {
return currency;
}
public Double value() {
return value;
}
}
Then in Java 8, you can create a comparator with the same behavior:Comparator<Money> comparator = Comparator.comparing( Money::currency ).thenComparing( Money::value );
Another class can support the interface. ComparableAnd then TableRowSorter Use it. compareTo♪ There's still a need to redesign. tableModel.getColumnClass( int column )I want him back. Money.class For the right column.