1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
| public class RowSorterDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTable());
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static Component createTable() {
Object[][] rowData = {
{ 1, "Margarita", 6.5d, true },
{ 2, "Pina Colada", 10.5d, true },
{ 3, "Mojito", 9.5d, true },
{ 4, "Black Russian", 8.5d, true },
{ 5, "Virgin Mojito", 5.5d, false }
};
String[] titles = { "Id", "Nom", "Prix", "Alcoolisé" };
JPanel panel = new JPanel(new BorderLayout());
JTable table = new JTable(rowData, titles);
TableRowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(table.getModel());
/* // Java 7 : comparateurs dédiés
rowSorter.setComparator(0, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
}
);
rowSorter.setComparator(1, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
);
rowSorter.setComparator(2, new Comparator<Double>() {
@Override
public int compare(Double o1, Double o2) {
return o1.compareTo(o2);
}
}
);
rowSorter.setComparator(3, new Comparator<Boolean>() {
@Override
public int compare(Boolean o1, Boolean o2) {
return o1.compareTo(o2);
}
}
);*/
// java 7 - Comparateur de comparable
Comparator<Comparable<Object>> comparator = new Comparator<Comparable<Object>>() {
public int compare(Comparable<Object> o1, Comparable<Object> o2) {
return o1.compareTo(o2);
}
};
for(int i=0; i<table.getColumnCount(); i++) {
rowSorter.setComparator(i, comparator);
}
/* // java 8
for(int i=0; i<table.getColumnCount(); i++) {
rowSorter.setComparator(i, Comparator.naturalOrder());
}*/
table.setRowSorter(rowSorter);
panel.add(table.getTableHeader(), BorderLayout.NORTH);
panel.add(new JScrollPane(table));
return panel;
}
} |