Calculating Fields
Just like lookup fields, calculated fields are virtual fields which you can add to a DataTable
object (in this case the Tasks
table). A calculated field differs from a lookup field in that rather than looking up its value from another table based on a key, it will calculate its value using code which we provide. Calculated fields in Data Abstract work exactly the same way as they do in any other dataset.
To demonstrate this we are going to improve how the data from the Done column is presented. We have a couple of possible options:
- Show a checkbox which is clear when the task is open, and checked when the task is done
- Show the text Open when the task is open, and Done when the task is done.
For ease of demonstrating calculated fields, we will use the later and leave the former as an exercise for the reader.
Setting up the Calculated Field
In DataModule.java
we add our new CalculatedDataColumn
after the LookupDataColumn
we added on the previous page.
The CalculatedDataColumn
's constructor takes three arguments:
- the name of the column, here we set it to
Status
- the column's data type, here we set it to a
String
- an
Evaluator
class, here we create an anonymous class using the new Lambda functionality to remove the boiler plate code. We retrieve the value from theDone
column of thedataRow
and return the stringsDone
orOpen
based on its value.
private void setupTable() {
//snipped code
CalculatedDataColumn calculatedDoneColumn = new CalculatedDataColumn("Status", String.class, dataRow -> {
long doneAsLong = ((Long)dataRow.getField("Done")).longValue();
return doneAsLong == 1 ? "Done" : "Open";
});
tasksTable.getColumns().add(calculatedDoneColumn);
}
Creating the CalculatedDataColumn
without the new Lambda functionality in Java looks like this
CalculatedDataColumn calculatedDoneColumn = new CalculatedDataColumn("Status", String.class, new CalculatedDataColumn.Evaluator() {
@Override
public Object evaluate(DataRow dataRow) {
long doneAsLong = ((Long)dataRow.getField("Done")).longValue();
return doneAsLong == 1 ? "Done" : "Open";
}
});
Display the Calculated Field
Swap over to TodoApp.java
and change the tweakTable
method to use the new CalculatedDataColumn
we added to the table model. Simply change the name of the column passed to getColumn
from Done
to Status
.
private void tweakTable() {
// snipped code
// TableColumn statusColumn = this.table.getColumn("Done");
TableColumn statusColumn = this.table.getColumn("Status");
// snipped code
}
Now when you run the app now you will see that the Status
column displays the appropriate text rather than 0 or 1.
Now that we are happy with how the data is presented to the user, its time that we add the ability to add, edit and delete tasks. Over the next few pages thats exactly what we shall do.