Open Source & Free  

Sortable Table

Sortable Table

Header Image

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

Leave a Reply