A Java Model View Controller example (Part 3)

<< Back to Part 2 of my Java MVC Example

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 EditProcessDialog.
  • This triggers an okButton actionPerformed event. This event is caught by the ProcessController (or perhaps by a smaller AddProcessController).
  • The controller validates the user data.
  • If there is a problem with the data, the EditProcessDialog remains shown, with an error message indicating the problem.
  • Otherwise, if the the data is okay, the controller inserts the new Process into the database using a ProcessDao object, with a method call that looks like this: processDao.insert(process);
  • If the database insert is successful, the controller also add the new Process to our internal list of Process objects, like this: processes.add(process);
  • Because the JTable's TableModel already has a reference to my processes object, it already has the new data, and the last thing I need to do is to tell the TableModel to fire its fireTableDataChanged event. Firing this event tells the listeners of this event that the TableModel data has changed, and you're going to want to repaint yourself. In this example, this specifically means that the MainProcessTable will repaint itself, correctly showing the new data. If other GUI components have registered themselves as listeners of the MainProcessTableModel, they will also be updated.

Model View Controller (MVC) Java example - summary

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.

<< Back to Part 2 of my Java MVC Example

Related Model View Controller (MVC) content

Before I leave, here are links to some of our other Model View Controller (MVC) content:


Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.