In this case, its preferable to use object composition than inheritance as you are not extending state/behavior in any of the Objects (DynamicForm, ListGrid, ListGridRecord).
Prefer composition over inheritance?
Why use inheritance at all?
You can use object composition as explained below.
One thing to understand is, records need to be added to the grid on button clicks/events.
You are trying to use setData during screen initialization.
Instead, setData (rather addData) must be called from button event handler.
Method to initialize grid
private ListGrid getListGrid() {
// preparing grid fields
ListGridField fname = new ListGridField("fname", "First Name");
ListGridField lname = new ListGridField("lname", "Last Name");
// creating and configuring grid
ListGrid grid = new ListGrid();
grid.setWidth100();
grid.setHeight100();
grid.setFields(fname, lname);
return grid;
}
Method to initialize form. Have to pass grid in order to add/update records on button events.
private DynamicForm getDynamicForm(final ListGrid grid) {
// preparing form items
final TextItem fname = new TextItem("firstName", "First Name"); // its better to explicitly specify both name and title
final TextItem lname = new TextItem("lastName", "Last Name");
ButtonItem saveButton = new ButtonItem("Save");
saveButton.setStartRow(true);
saveButton.setEndRow(false);
saveButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent clickEvent) {
String fn = fname.getValueAsString();
String ln = lname.getValueAsString();
Record record = new Record();
record.setAttribute("fname", fn); // record attribute names must match grid field name
record.setAttribute("lname", ln);
grid.addData(record); // addData should be used to add new records per save operation
// setData should be used to set all records in grid per save operation
// in this case, its probably not what is required, as this will overwrite previous records in grid
// resulting, only one record left in grid after every save operation
// grid.setData(new Record[]{record});
}
});
// creating and configuring form
DynamicForm form = new DynamicForm();
form.setWidth100();
form.setHeight(135);
form.setNumCols(6);
form.setErrorOrientation(FormErrorOrientation.RIGHT);
form.setFields(fname, lname, saveButton);
return form;
}
Putting it together
ListGrid grid = getListGrid();
DynamicForm form = getDynamicForm(grid);
...
formSection.setItems(form);
...
gridSection.setItems(grid);
...
sections.setSections(formSection, gridSection);