Reputation: 796
I have a Container class which is extends from BeanItemContainer. I want to add a ItemSorter to DATE_CREATED attribute to sort the values in descending order.
Container class.
public class NoteContainer extends BeanItemContainer<CaseNote> implements Serializable
{
private static final long serialVersionUID = -5926608449530066014L;
public static final String DATE_CREATED = "dateCreated";
public static final String CREATED_BY = "createdBy";
public static final String TEXT = "text";
public static final String ACTION = "Action";
public static final Object[] NATURAL_COL_ORDER = new Object[] {
ACTION, DATE_CREATED, CREATED_BY, TEXT
};
public static final String[] COL_HEADERS_ENGLISH = new String[] {
"ACTION", "Date Created/Updated", "Created/Updated By", "Note"
};
/**
* Default Constructor.
*
*/
public NoteContainer()
{
super(CaseNote.class);
}
}
CaseNote is an Entity class, and inside that DATE_CREATED
is in java.util.Date
format.
Please provide a proper solution...
related to Sort vaadin Table
Thanx in advance.
Upvotes: 2
Views: 5395
Reputation: 2456
BeanItemContainer already has everything prepared to set an ItemSorter easily. You can use this function:
public void sort(Object[] propertyId, boolean[] ascending)
So for example you can add a sortByDate() function to your container to do this. Here three example classes.
The Bean:
public class CaseNote {
private static final Random R = new Random();
private static final long Y_IN_MILLIES = 1000l * 60l * 60l * 24l * 365l;
private Date dateCreated = new Date(System.currentTimeMillis() - Math.round(R.nextDouble() * Y_IN_MILLIES));
private String text = UUID.randomUUID().toString();
public String getText() {
return text;
}
public Date getDateCreated() {
return dateCreated;
}
}
The Container:
public class NoteContainer extends BeanItemContainer<CaseNote> {
public NoteContainer() {
super(CaseNote.class);
}
public void sortByDate() {
sort(new String[] { "dateCreated" }, new boolean[] { false });
}
}
The test UI:
public class TestUI extends UI {
@Override
protected void init(VaadinRequest request) {
NoteContainer nc = new NoteContainer();
for (int i = 0; i < 10; i++) {
nc.addItem(new CaseNote());
}
nc.sortByDate();
for (int i = 0; i < 10; i++) {
nc.addItem(new CaseNote());
}
Table t = new Table("MyTable", nc);
setContent(t);
}
}
Note: The Items added after calling the sortByDate() function are not sorted. If you want to have the items sorted after every insert, you could overwrite the addItem() functions, so that they call sort() after adding the item.
Upvotes: 4