Changes required for saving my own objects instead of just Strings
This time, instead of creating and saving Strings, I create and save Person objects. What is a Person object? Well it’s whatever I want it to be. I created it. I have given it just two fields: firstName and lastName, just to keep it simple, but obviously it could be arbitrarily complex (ie as complex as you like). You can only set the names of your Person object by passing Strings to the constructor, as you will see below.
In addition to creating the Person class, I have had to make some changes to all classes except the BasicApp class. A run-down of these changes is below, but you can also just compare the code with my last version if you like.
- The AppLogic now has an array of Person objects, not Strings. The add() method has had to change to accept a Person, not a String. I have also coded a basic edit() method that I will go through in class.
- The MainForm has hardly changed, except to ask the Subform for a Person, rather than a String.
- The Subform now has two fields, one for firstName and one for lastName, and instead of a getText() method, it now exposes a getPerson() method, which takes the values from the text fields, creates a new Person object, and returns it.
The edit functionality
There is now an edit button on the main form. In the MainForm code it is referred to as button1 (very lazy of me, I know).
Look at the MainForm.button1ActionPerformed() code now.
- We get the index of the selected person from the list.
- We ask the appLogic for the corresponding Person object.
- We instantiate the subform and populate its fields using the values from the Person object.
- [The user then edits the textfields of the subform]
- We then ask for the new Person from the subform and pass it to the edit() method of the appLogic. Notice that we have to specify WHERE in the array it should go by providing the index. We can’t just add it, because then we won’t overwrite the old version of the Person objects.
- We then update our list, as before.