I'm currently building a Java GUI application and I'm about to implement something that seemingly requires a great deal of thinking, at least for someone as relatively inexperienced as me.
is as follows: I have a class Customer
at domain level, that holds a collection of jobs, which is a class too (Job
). The application is for a fictious gardening company that wants to manage its customers and the jobs it does for them.
At GUI level, I have a jList for all the customers, with a custom listmodel that extends AbstractListModel
. This part of my application works perfectly, I can add/edit/remove customers easily and as it should be.
now is to implement a jTable that should show the jobs for the customer selected in the jList.
No doubt I'll need a custom TableModel
, the question is: where to get the data from? It should be noted that the collection of jobs in the Customer
class is an ArrayList
, and the class has no method that returns this ArrayList directly, it is only possible to get a copy, since I don't want it to be possible to mutate the collection in the class directly from a public context.
Is to let the tablemodel have a method to change the internal collection, with a customer
parameter. When the index in the jList
changes, that method should be invoked, so that the jTable represents the Job
s that have been done for the customer.
When I have to edit/create/remove a job, the changes are always done on the tablemodel first, which will propagate the changes to the customer
object (in case of a new job or job removal).
Is that a good way to implement it? I feel it is not, because if I forget to do any changes to a Job
via the tablemodel, and on the Customer
or Job
directly, there will be inconsistency and trouble. Are there better ways? If it involves changing other stuff, I do not mind.
I lack some knowledge on the different Collection
s in java. I usually just go with ArrayList
, like in this case in Customer
for (mutable) jobs. Is there a better collection for this?
Not saying this is the best way to implement this, but this is how I would do it
Customer
which updates the Job
collection fires eventsJob
s for a certain Customer
can then listen for those events and update itself accordinglyCustomer
So nothing changes on your current edit/create/remove/add job code. That keeps working with your Customer
and does not even know a TableModel
exists. The TableModel
works also directly against the Customer
and does not even know there might be UI to edit/create/remove/add jobs. It just listens for any changes made to the job collection and updates itself accordingly.
It seems like a very bad idea to make the changes to the job list in all parts of your code through the table model. The Customer
is your model, and the JTable
is the view (MVC pattern anyone). The fact the JTable
needs a different representation of your model (a TableModel
) is a side-effect.