Sometimes I get a question on stack overflow that triggers a “yes this should be easy” reflex. I got such a question a couple of weeks ago when I implemented the animated gif support cn1lib and I had another one last week which asked about sorting tables.
This is actually pretty easy to do but it’s just something we didn’t get around to. So I just implemented it and decided this would make a lot of sense in the core API. Sortable tables make a lot of sense and ideally should be the default.
So I added support for this directly into Codename One and you can now make a table sortable like this:
Form hi = new Form("Table", new BorderLayout());
TableModel model = new DefaultTableModel(new String[] {"Col 1", "Col 2", "Col 3"}, new Object[][] {
{"Row 1", "Row A", 1},
{"Row 2", "Row B", 4},
{"Row 3", "Row C", 7.5},
{"Row 4", "Row D", 2.24},
});
Table table = new Table(model);
table.setSortSupported(true);
hi.add(BorderLayout.CENTER, table);
hi.add(NORTH, new Button("Button"));
hi.show();
Notice this works with numbers, Strings and might work with dates but you can generally support any object type by overriding the method protected Comparator createColumnSortComparator(int column)
which should return a comparator for your custom object type in the column.
10 Comments
Thank you very much! 🙂
First question: I tested your code in a new Netbeans project, but it doesn’t compile because it «cannot find symbol table.setSortSupported(true);». I’ve seen that you updated the API, but… how do I update Netbeans?
Second question: in your code, is the Table sorted by the third column? How can I choose which column to order by?
Thank you for any help (and for your work in vacation time…)
Make sure to update the libraries by opening Codename One Settings -> Basic -> Update Client Libs.
Ok, now it compiles… but the table is not sorted (using exactly your code). How can I sort it according to the values in third column? Thank you
Click the columns to sort them and again to flip ascending/descending direction.
Very nice you guys are amazing!!!
Thanks for sharing! this is such a great help this is worth to share!
Ok. Is there any way to get a column already selected for ordering (in ascending or descending direction) before any user input, for example on [myForm.show](http://myForm.show)() or myForm.revalidate()?
I’ll add a sort(column, ascending) method to allow this.
Thank you! 😀