Monthly Archives: January 2014

MVC Implementation in Java Swing By JFrame & JInternalFrame Approach

MVC Brief

MVC (Model View Controller) is a layer representation to build an application. MVC must separate source code files structure into 3 layers which are Model, View and Controller.
MVC is needed to build large application so that it is easier to maintain and develop. Changes in one layer doesn’t effect to another layers so it is loose coupling.

I will write short explanation about MVC. Model layer is a business logic. It contains entity of a business object i.e customer, product, operation, sales details etc.
Please note that Model is not database access object. Database access is closely related to Model but it is not Model itself. Model uses Database access object to produces business objects.
View layer is simply an UI presentation. Controller layer contains methods to handle user events such as click, keypress, etc. This controller layer sometimes confusing since user events is inside View layer.

Although user events is inside View layer but the handler method itself could be as/in Controller. So controller plays as a bridge between Model & View. It chooses which model object should be accessed and which view sould be presented for that related user event.

To apply complete MVC layers we need 3 source code files at minimum. These 3 represent each one of Model/Controller/View.
I said ‘complete MVC’ because of sometimes application Controller and View combined into one layer only. This simpler M(VC) only separates Model and its View. For this kind of method, it requires 2 files only.
I think most of Swing Application uses this M(VC) layer. View & User events directly access Model objects without a Controller.

Swing MVC with JFrame & JInternaFrame

To think about MVC in Swing, I need to figure out how to separate each one of MVC layers efficiently. I came accross to JFrame & JInternalFrame approach.

Practically, I have main JFrame with child/internal JInternalFrame. Main JFrame acts as a Controller and JInternalFrame is a View. Model represents business logic objects.

Here in this blog post, I will show you a MVC implementation with simple example. This example just shows list of products and also has add new product functionality.
As I said earlier that Main JFrame is a Controller and so between main JFrame & JInternalFrame as View class source code must be separated. Also Model layer off course.

If you want to download my NetBeans Project for build this app then please go to Download Swing MVC Project Source.
However, I will write this projcct inside ‘sourcecode’ post.
Continue reading