Currently I have a JTable
that uses RowSorter
, but when I click the header that I want it to sort in, it displays the rows in a weird order
You can set the column type for a JTable by setting its model explicitly like in the following example
setModel(new DefaultTableModel(new Object[0][], new String[] {
"SELECT", "WHERE", "FIELD", "TYPE" }) {
Class[] types = { Boolean.class, Boolean.class, String.class,
String.class };
boolean[] canEdit = { true, false, false, false };
@Override
public Class getColumnClass(int columnIndex) {
return this.types[columnIndex];
}
public boolean isCellEditable(int columnIndex) {
return this.canEdit[columnIndex];
}
});
Give your column classes like this (here column one and two are Boolean and the rest String.
Class[] types = { Boolean.class, Boolean.class, String.class,String.class };
You're treating the row contents as text. Your sort order is alphabetical rather than numerical. If you treat the contents as numbers it should work itself out.
To meet your requirement, you just sets the Comparator for RowSorter to use when sorting the specified column. The code somewhat like below:
table.setAutoCreateRowSorter(true);
TableRowSorter<DefaultTableModel> rowSorter = (TableRowSorter<DefaultTableModel>)table.getRowSorter();
rowSorter.setComparator(5, new Comparator<String>() {
@Override
public int compare(String o1, String o2)
{
return Integer.parseInt(o1) - Integer.parseInt(o2);
}
});
You must add the below code to your actual code that doesn't sort your column as Integer.
Your actual code to build your JTable is:
DefaultTableModel modeloT = new DefaultTableModel();
// But Sorts the column of numbers in wrong way. 1,11,2,25,......
SOLUTION:
DefaultTableModel modeloT = new DefaultTableModel() {
// Defining the type of column on your JTable. I wish sort my second column as a numeric (1,2,11), not String (1,11,2). For that I defined the second class as Integer.
Class[] types = { String.class, Integer.class, String.class };
boolean[] canEdit = new boolean [] {
false, false, false
};
// You must add this Override in order to works sorting by numeric.
@Override
public Class getColumnClass(int columnIndex) {
return this.types[columnIndex];
}
// This override is just for avoid editing the content of my JTable.
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
I was also trying to achieve what you were trying to do and I struggled to understand how to do it myself. The way I achieved the "proper" sorting was as such:
DefaultTableModel model = new DefaultTableModel(row, col){
@Overrride
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
});
To expand on @aaamos' answer, verify that your TableModel
returns Number.class
(or a suitable subclass) from getColumnClass()
. There's a related example here.