Now we need to make the ProductViewer
display the products that have been saved in the DAO.
In the source view, add a field to ProductViewer
that is an instance of your DAO class.
We need to get the product objects out of the DAO and put them into the JList
.
Since Swing components use the Model-View-Controller mechanism, we need to create a model (not to be confused with modal --- they are two entirely different concepts) that will hold the data and then tell the list component about the model.
The default model classes in Swing are outdated and clunky, so we have written one that is a bit easier to work with:
Create a new class named SimpleListModel
. It should go in a package named helpers
Open the following URL in a web browser:
https://isgb.otago.ac.nz/info202/shared/useful-files/blob/master/helpers/SimpleListModel.java
Copy and paste the code into your SimpleListModel
class.
Refer to the Swing/List Components (JList and JComboBox)/Displaying Objects in a List/Displaying%20Objects%20in%20a%20List) section in the reference.
Add a SimpleListModel
field to your ProductViewer
dialog (step 1 from the reference). This model is for holding the products that will be displayed so name it productsModel
.
Call the method on the DAO object that gets all of the products. Store the result in a variable.
Update the contents of the model field using the list of products that you just retrieved from the DAO (step 2 in the reference).
Tell the JList
component about the model (step 3).
Test the system again. You should now be able to add some products using the product editor dialog and then see them in the product viewer dialog.
If you are not happy with how the products are being displayed then you can change the toString()
method in the product domain class.
You can close the issue for this feature now.