MVC: Handling data-changing events
Whenever the user adds, edits, or deletes data, such as our
Process data, all the proper GUI components need to be notified of this event so they can properly update their displays. In this application, when a user adds a new
Process, this means that we need to update our
MainProcessTable. We implement this as follows:
- The user presses the OK button on the
- This triggers an okButton actionPerformed event. This event is caught by the
ProcessController(or perhaps by a smaller
- The controller validates the user data.
- If there is a problem with the data, the
EditProcessDialogremains shown, with an error message indicating the problem.
- Otherwise, if the the data is okay, the controller inserts the new
Processinto the database using a
ProcessDaoobject, with a method call that looks like this:
- If the database insert is successful, the controller also add the new
Processto our internal list of Process objects, like this:
- Because the JTable's
TableModelalready has a reference to my
processesobject, it already has the new data, and the last thing I need to do is to tell the
TableModelto fire its
fireTableDataChangedevent. Firing this event tells the listeners of this event that the
TableModeldata has changed, and you're going to want to repaint yourself. In this example, this specifically means that the
MainProcessTablewill repaint itself, correctly showing the new data. If other GUI components have registered themselves as listeners of the
MainProcessTableModel, they will also be updated.
Summary of my Model View Controller (MVC) Java example
I hope this has served as a good example of how to use the Model View Controller (MVC) pattern in a real-world software application. If you'd like me to add any more detail to this article, or you have any other questions or comments, just use the comment form below.
Related Model View Controller (MVC) content
Before I leave, here are links to some of my other Model View Controller (MVC) content:
- Model View Controller - definitions and examples
- A terrific Model View Controller (MVC) diagram
- A Java Model View Controller example, Part 1
- A Java Model View Controller example, Part 2